0

I am new to Java and I am trying to understand Nested while loops. I am trying to write a program that will print the following output:

999999999 on the top line,
88888888 on the next,
7777777 etc,
666666 etc,
55555
4444
333
22
1

I was easily able to do this using a for loop, but now I want to do the same with a While Loop. The issue is that my code, in its current state, only prints the first line of nines, and then it looks like the inner While loop doesn't run anymore afterwards.

I am super perplexed, I don't think any of my criteria are Tautologies, but I don't understand tautologies that well. Please explain what is wrong with my loop logic. Loops are still a lot of mystical voodoo to me.

int outer = 9;
int inner = 1;

while (outer >= 1)
    {   
        while(inner <= outer)
            {
                System.out.print(outer);
                inner++;
            }
        System.out.println();
        outer--;
    }

2 Answers 2

1

You have to reset the value of inner after the second while loop.

while (outer >= 1){   
        while(inner <= outer){
                System.out.print(outer);
                inner++;
        }
        inner = 1;
        System.out.println();
        outer--;
 }

Also note that a quick use of the debugger, or simply with a pen and a paper to see what are the values of each variables at each iteration, would make you see this more faster than asking the question here.

Sign up to request clarification or add additional context in comments.

3 Comments

I just realized this literally as soon as I posted lol. Thank you for the help! I feel like such a rookie.
@user2993456 I generally find it helpful (when am learning) to dry run the code on a piece of paper by writing down the values of variables at each state of the loop.
Thanks for the advice. I got ahead of myself this time, but I will try your method in the future for sure!
0

You need to reset inner each time:

while (outer >= 1) {   
    inner = 1; // ADD THIS LINE
    while(inner <= outer)
        {
            System.out.print(outer);
            inner++;
        }
    System.out.println();
    outer--;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.