简体   繁体   English

有没有一种方法可以使用while循环来计算迭代次数?

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

Is there a way in which the program can count the number of iterations in which it took for the variable " counter " to reach its limit? 程序是否可以计算变量“ counter ”达到其极限所需的迭代次数? I'm writing a basic program that demonstrates the use of a while loop and have been asked to display the number of iterations which have been printed out. 我正在编写一个基本程序,该程序演示了while循环的用法,并被要求显示已打印出的迭代次数。

PS Sorry if there are any errors in the indentation/formatting of the code, I'm new to Java/programming. PS对不起,如果代码的缩进/格式设置中有任何错误,我是Java /编程新手。 Thanks in advance. 提前致谢。

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++;
        }
    }
}

If I've understood your question correctly, you're looking for something to keep incrementing the value as part of the loop rather than as a separate statement. 如果我正确理解了您的问题,那么您正在寻找某种东西来使值递增,这是循环的一部分,而不是单独的语句。 Well, you could make it more terse using the ++ operator. 好吧,您可以使用++运算符使其更简洁。

int x = 0;

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

Some Detail 一些细节

x++ is shorthand for x = x + 1 . x++x = x + 1简写。 There is a slight caveat with this. 对此有一点警告。 x++ means return the value of x, then order it. x++表示返回x++的值,然后对其进行排序。 So... 所以...

while(x++ < 100)

Will print out 0,1,2,3,4,5....99 (therefore iterating exactly 100 times) However, if you have ++x instead, this says to increment then return. 将打印出0,1,2,3,4,5 .... 99(因此精确地进行了100次迭代)。但是,如果您使用++x ,则表示先递增然后返回。 So: 所以:

while(++x < 100)

would print out 1,2,3,4,5...99 (and iterate 99 times). 将打印出1,2,3,4,5 ... 99(并重复99次)。

Just added a counter variable to track the loop execution count. 刚刚添加了一个计数器变量来跟踪循环执行计数。

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);
 }
}

Hope this helps! 希望这可以帮助!

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

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