首页 > 解决方案 > 为什么我的 else 语句在 'while-loop' 中执行,但不在 JAVA 中的'for-loop' 中执行

问题描述

我对 Java 有点陌生,试图通过复数视觉和几本参考书自学 - “一日学习 Java,学得好”。

我遇到了一种特殊情况,在“while 循环”内,我的 else 块执行大于 100 的结果。但是对于类似的东西,在“for 循环”语句内,else 部分不执行一点也不。我很想更多地了解为什么我在 while 循环中所做的工作按我的预期工作,但不是当我在 for 循环中做类似的事情时。

谢谢你。

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: - 只执行语句的“if”部分。不确定为什么没有执行 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!!!!");
        }
    }

标签: javaloopsfor-loopwhile-loop

解决方案


for 循环在每个循环周期结束时执行最后一条语句。这意味着在 for 循环中,lval2被加倍,并立即检查它是否大于 100(for 循环的条件部分)。这意味着如果它大于 100,它甚至不会再次进入循环,因此不会到达 else 语句。

For 循环在循环开始时执行一次初始化(第一部分)。然后他们在循环的每个循环之前检查条件(第二部分),并在每个循环结束时执行增量(第三部分)。

希望这有帮助。


推荐阅读