ccbadger ccbadger - 2 months ago 9
Java Question

Java - How to create alternating triangle pyramid?

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.

Answer

This method will work fine:

public void printPyramid (int input) {
    for (int row = 1; row <= input; row++) {
        for (int whitespace = input - 1; whitespace >= row; whitespace--) {
            System.out.print(" ");
        }
        System.out.print("*");
        for (int circle = 1; circle < row; circle++) {
            System.out.print("o*");
        }
        System.out.println();
    }
}
                         *
                        *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*
                *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*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*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*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*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*