Search code examples
javaloopsfor-loopnested-loops

Coding this pyramid pattern with user input and spaces in Java?


I'm completely new to coding and my teacher is terrible at explaining things. I have no idea what's going on in the class, and I really need help with this! I've made lots of pyramid patterns before, but this is one I can't figure out.

I know how to get user input too, but I just need help understanding why this won't work. He briefly explained how to code this problem to us, but it doesn't work no matter how many times I change and try it.

I have to create a pyramid using the number of lines the user inputs. So if the user entered 5, this is what it should look like:

    *
   **
  ***
 ****
*****

So the number of spaces on the first line is four, the second one has three spaces, and so on until you get to zero.

This is the code (which gives a completely inaccurate output):

System.out.print("\f");
System.out.println("Enter a valid number between 1 and 20."); 
int num = 0;
int counter = 1;
num = keyNum.nextInt();
for (int i = 1; i == num; i++)
{
    for (int j = 1; j == (num -= counter); j++)
    { 
        System.out.print(" ");
    }
    for (int k = 1; k == counter; k++)
    { 
        System.out.print("*");
    }
    System.out.println("");
    counter++;
} 

Please help! I feel so stupid.


Solution

  • It's mostly right, but you are starting the loops from 1, but they really should be starting from 0, and the condition in the for loops shouldn't have == which just makes it run once.

    for (int i = 0; i < num; i++) {
        for (int j = 0; j <= (num - counter); j++) {
            System.out.print(" ");
        }
    
        for (int k = 0; k < counter; k++) {
            System.out.print("*");
        }
    
        System.out.println("");
    
        counter++;
    }