Learning the nested while loop in Java

33,750

Solution 1

The inner loop runs until i = 7. After it finishes, i is still 7, so it won't run again until you change i to some other value.

If you change it to a do - while loop, it should clear up the problem.

Solution 2

Simply because you don't reset i before you start the inner loop (or after you end it.)

Therefore, in the second, and subsequent iterations of the outer loop, you get to the inner while statement, but the condition i != 7 is still false and you don't execute the inner loop body.

A simple fix would be to add i = 0 immediately before the inner while.

A more elegant fix would be to change the inner while into a do ... while.

Share:
33,750
lqdc
Author by

lqdc

Updated on February 12, 2020

Comments

  • lqdc
    lqdc about 4 years

    In this program, the inner loop generates random numbers out of 100 and then stops generating them when the random number is 7. The outer loop repeats the inner loop 100 times.
    why doesn't my outer loop keep redoing the inner loop?
    It seems like it only did it once.

    package test;
    
    
    public class Loops {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int i = 0;
            int sum = 0;
            int counter = 0;
            String randomNumberList = " ";
            int c = 0;
            while (c != 100){
    
                while (i != 7) {
                i = (int) (101 * Math.random());
                sum += i;
                ++counter;
                randomNumberList += " " + i;
                }
            System.out.print("\n loop repeated" + counter+ " times and generated these numbers: " + randomNumberList);
                ++c;
            }
    
        }
    
    }