I am trying to create a triangle pyramid of alternating "*" and "o" characters, with the number of rows being based on user input. The expected output I am trying to achieve, if the user inputs "6" for the number of rows, is:
*
*o*
*o*o*
*o*o*o*
*o*o*o*o*
*o*o*o*o*o*
The code I have written to achieve this is:
String star = "*";
String circle = "o";
System.out.println("Please enter number of rows: ");
int rows = in.nextInt();
for (int i = 0; i < rows; i++){
for (int j = 0; j < rows-i; j++){
System.out.print(star);
}
for (int k = 0; k <= i; k++){
System.out.print(circle);
}
System.out.println();
}
However, the output from my code does not match the pyramid above. The output of my code, with a user input of "6", is:
******o
*****oo
****ooo
***oooo
**ooooo
*oooooo
After spending the last three hours scouring both this website and others, I have still come up lost on how to alternate the characters, how to have the correct number of characters in each row, and how to format the pyramid as the expected output is. I don't know if my code is completely wrong, or if I am only missing a part to make it work correctly, but any advice or references is greatly appreciated.
You could approach it another, far simpler, way.
In pseudo code:
n
spaces"*"
to itn
times, each iteration of the loop:
" *"
with "*O*"
This recognises a simple way to create the first line, and a simple way to create the next line from the previous line. Each replacement will match only the last (leading) space and the first star, replacing the space with a star, the star with an O and adding a star.
Usually the best way to solve a hard problem is to look at it in a way that makes it a simple problem (or a collection of simple problems).
A couple of ways to create a String of n
spaces:
' '
each iterationnew String(new char[n]).replace('\0', ' ')
How to replace certain characters of a String with other characters:
str = str.replace(" *", "*O*");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With