[英]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.