Problem Description:
1. Prompt the user to enter a whole number from 1 to 9 inclusive. The number zero (0) will be used
to exit the application. If any other number is entered, then an error message shall be displayed
and then the prompt to enter a whole number will be re-displayed.
2. Create a pyramid structure by using only the odd numbers without going over the number entered
in by the user. For example:
If the user entered in 8, then construct your pyramid using the numbers 1, 3, 5, and 7.
3. The pyramid shall be constructing by repeating the odd number the same number of times as its
value. For example:
The number 1 will be repeated only once.
The number 3 will be repeated three times.
The number 5 will be repeated five times.
4. The pyramid shall be centered accordingly, with the highest odd number being the most left align.
This will require you to calculate the center of the pyramid based upon the highest odd number.
The number one (1) will always be in the center
1
Expert's answer
2012-02-17T07:15:13-0500
import java.util.Scanner;
public class Pyramid {
//Scanner for reading keys pressed
private static Scanner keyboard = new Scanner(System.in);
/**
* function makes center alignment
* @param data is String for alignment
* @param length is length of the String in text.
* @return formatted String
*/
private String formatCenter(String data, int length){
StringBuilder res = new StringBuilder();
for(int i = 0; i < (length - data.length())/2; i++){
res = res.append(' ');
}
res.append(data);
for(int i = res.length(); i <= length; i++){
res.append(' ');
}
return new String(res);
}
public void main(String [] args){
String userInput;
StringBuilder output = new StringBuilder();
int length = 50;
int n;
while(true){
System.out.println("Input number from 1 to 9 inlusive, please. "
Comments
When I run in JCreator I get the following error: java.lang.NoSuchMethodError: main Exception in thread "main" Process completed.
Leave a comment