簡體   English   中英

有沒有一種方法可以使用while循環來計算迭代次數?

[英]Is there a way to count iterations using a while loop?

程序是否可以計算變量“ counter ”達到其極限所需的迭代次數? 我正在編寫一個基本程序,該程序演示了while循環的用法,並被要求顯示已打印出的迭代次數。

PS對不起,如果代碼的縮進/格式設置中有任何錯誤,我是Java /編程新手。 提前致謝。

public class Main {
    public static void main(String[] args) {
        for (int counter=2; counter<=40; counter+=2) {
            System.out.println(counter);
        }
        System.out.println("For loop complete.");

        int counter = 1;
        while (counter <= 500) {
            System.out.println(counter);
            counter++;
        }
    }
}

如果我正確理解了您的問題,那么您正在尋找某種東西來使值遞增,這是循環的一部分,而不是單獨的語句。 好吧,您可以使用++運算符使其更簡潔。

int x = 0;

while(x++ < 100) {
    System.out.println(x);
}

一些細節

x++x = x + 1簡寫。 對此有一點警告。 x++表示返回x++的值,然后對其進行排序。 所以...

while(x++ < 100)

將打印出0,1,2,3,4,5 .... 99(因此精確地進行了100次迭代)。但是,如果您使用++x ,則表示先遞增然后返回。 所以:

while(++x < 100)

將打印出1,2,3,4,5 ... 99(並重復99次)。

剛剛添加了一個計數器變量來跟蹤循環執行計數。

package main;
public class Main {
public static void main(String[] args) {
    for (int counter=2; counter<=40; counter+=2) {
       System.out.println(counter);
    }
    System.out.println("For loop complete.");

    int counter = 1;
    int loopExecCounter = 0;
    while (counter <= 500) {
        loopExecCounter = loopExecCounter + 1;
        System.out.println(counter);
    counter++;
    }
System.out.print(loopExecCounter);
 }
}

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM