简体   繁体   中英

Why does my else statement execute in a 'while-loop' but does not execute in a 'for-loop' in JAVA

I'm a bit new to Java, trying to self-learn via pluralsight and several books for reference - 'Learn Java in one day and learn it well'.

I've run in to a peculiar situation where, inside of a 'while loop' my else block executes for results that are greater than 100. However for something similar, inside of a 'for loop' statement, the else part does not execute at all. I'd love to understand more as to why what I have done in a while loop works as I expect, but not when I do something similar in a for-loop.

Thank you.

While loop: - executes perfectly, both the if statement and the else statement

    int wVal = 1;
    while(wVal < 100) {
        System.out.println(wVal);
        wVal *= 2;
        if (wVal <100 ){
            System.out.println("going back to the top to check if wVal is less than 100");
        }else{
            System.out.println("We hit more than a hundred!!!");
        }
    }

For-Loop: - only executes the 'if' part of the statement. Unsure why the else statement has not been executed.

    System.out.println("Entering the for loop for lVal2");
    for (int lVal2 = 1; lVal2 <100; lVal2 *=2 ){
        if (lVal2 < 100) {
            System.out.println("The value of lVal2 is currently: " + lVal2);
            System.out.println("The multiplication is being done ....");
            System.out.println("Going back to the to the top unless we hit 100");
        }else{
            System.out.println("We hit more than a hundred!!!!");
        }
    }

The for loop executes the final statement at the end of every loop cycle. This means that in the for loop, lval2 is being doubled, and immediately after it is checking to see if it is greater than 100 (the condition part of the for loop). This means that if it is greater than 100, it won't even enter the loop again, and thus will not reach the else statement.

For loops execute the initialization (first part) once at the start of the looping. They then check the condition (second part) before every cycle of the loop, and the increment (third part) is executed at the end of every cycle.

Hope this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM