public class ForLoopDemo {
public static void runForLoop(int start, int stop, int increment) {
for (int counter = start; counter <= stop; counter = increment) {
System.out.println(counter);
}
}
}
public class ForLoopDemoRunner {
public static void main(String[] args) {
System.out.print("start 2 : stop 90 : increment 5");
ForLoopDemo.runForLoop(2, 90, 5);
}
}
出于某种原因,所有这些运行时应运行555(重复):
2 7 12 17 22 27 32 37 42 47 52 57 62 67 72 77 82 87
我的老师也让我们把它放在两种格式中。
答案 0 :(得分:3)
看看这个:
for(int counter = start; counter <= stop; counter = increment)
{
System.out.println(counter);
}
counter
始终低于stop
,因此循环会永远持续。
通过counter += increment
答案 1 :(得分:1)
你的柜台在同一个位置。请更新如下:
public static void runForLoop(int start, int stop, int increment )
{
for(int counter = start; counter <= stop; counter = counter + increment)
{
System.out.println(counter);
}
}
答案 2 :(得分:0)
请修改您的ForLoopDemo如下(我已经测试过):
public class ForLoopDemo {
public static void runForLoop(int start, int stop, int increment) {
for (int counter = start; counter <= stop; counter += increment) {
System.out.println(counter);
}
}
}
输出:
start 2 : stop 90 : increment 52
7
12
17
22
27
32
37
42
47
52
57
62
67
72
77
82
87