簡體   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