Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning the nested while loop in Java

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;
        }

    }

}
like image 535
lqdc Avatar asked Aug 23 '26 17:08

lqdc


2 Answers

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.

like image 89
Sam Dufel Avatar answered Aug 26 '26 11:08

Sam Dufel


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.

like image 20
Stephen C Avatar answered Aug 26 '26 11:08

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!