繁体   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

我对Java有点陌生,尝试通过pluralsight和几本书进行自学-'一天学习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 循环:- 仅执行语句的“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!!!!");
        }
    }

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

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

希望这有所帮助。

暂无
暂无

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

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