简体   繁体   English

为什么我的 else 语句在 JAVA 中以“while 循环”执行但不在“for 循环”中执行

[英]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'.我对Java有点陌生,尝试通过pluralsight和几本书进行自学-'一天学习Java并学好它'。

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.我遇到了一种特殊情况,在“while 循环”内,我的 else 块执行大于 100 的结果。但是对于类似的情况,在“for 循环”语句内,else 部分不执行根本。 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.我很想更多地了解为什么我在 while 循环中所做的工作如我所料,但当我在 for 循环中做类似的事情时却没有。

Thank you.谢谢你。

While loop: - executes perfectly, both the if statement and the else statement while 循环:- if 语句和 else 语句都完美执行

    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. For 循环:- 仅执行语句的“if”部分。 Unsure why the else statement has not been executed.不确定为什么没有执行 else 语句。

    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. for 循环在每个循环周期结束时执行最终语句。 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).这意味着在 for 循环中, lval2被加倍,并在检查它是否大于 100 之后立即检查它是否大于 100(for 循环的条件部分)。 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.也就是说,如果大于100,就不会再进入循环,也就不会走到else语句。

For loops execute the initialization (first part) once at the start of the looping. For 循环在循环开始时执行一次初始化(第一部分)。 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.希望这有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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