Java Question: Display a pattern of stars ‘*’ and lower case character ‘o’ in a
ID: 671781 • Letter: J
Question
Java Question:
Display a pattern of stars ‘*’ and lower case character ‘o’ in a proper format as suggested below.
Step1 : The first step is to read the user input. If the user input is invalid (not integer or not positive), the program displays the message below and break out of the switch-case (as shown in Output 3 and 4). *** Invalid number of rows *** (3 Pts)
Output 3: Please enter number of rows: -6 *** Invalid number of rows ***
Output 4: Please enter number of rows: Q *** Invalid number of rows ***
Step2: Create nested loops to print out a pattern of stars and lower case ‘o’. Your output should be well formatted (as shown in Output 5). (3 Pts) Output 5: Please enter number of rows: 9
*
*o*
*o*o*
*o*o*o*
*o*o*o*o*
*o*o*o*o*o*
*o*o*o*o*o*o*
*o*o*o*o*o*o*o*
*o*o*o*o*o*o*o*o*
When it is printed the * and 'o' should look like a pyramid not be alligned on the left.
Explanation / Answer
public class Pyramid {
public static void main(String args[]) {
int noof = 0;
final String FINAL_CHAR_REGEX = "[!@#$%^&*()[\\]|;',./{}\\\\:\"<>?]";
BufferedReader dataIn = new BufferedReader(new InputStreamReader(
System.in));
System.out.print("Please enter number of rows: ");
int flag = 0;
try {
String readVal = dataIn.readLine();
char password=readVal.charAt(0);
if (Character.isUpperCase(password)) {
flag = 1;
}
if (Character.isLowerCase(password)) {
flag = 1;
}
if (Character.isDigit(password)) {
noof = Integer.parseInt("" + password + "");
if (noof > 0) {
// generatePyramid(noof);
flag = 2;
} else {
flag = 1;
}
}else{
flag = 1;
}
switch (flag) {
case 1:
System.out.println("*** Invalid number of rows ***");
break;
case 2:
generatePyramid(noof);
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// String readVal=scanner.next();
}
private static void generatePyramid(int x) {
int i, j;
for (int y = 0; y < x; y++) { // number of row of '*'
for (i = y; i < x - 1; i++)
// number of space each row
System.out.print(" ");
for (j = 0; j < y * 2 + 1; j++)
// number of '*' each row
if (j % 2 == 0) {
// odd position
System.out.print("*");
} else {
// even position
System.out.print("o");
}
System.out.println();
}
}
}
Test 1 :
Please enter number of rows: 5
*
*o*
*o*o*
*o*o*o*
*o*o*o*o*
Test 2 :
Please enter number of rows: $
*** Invalid number of rows ***
Test 3 :
Please enter number of rows: -7
*** Invalid number of rows ***
Test 4 :
Please enter number of rows: E
*** Invalid number of rows ***
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.