我是java的初学者,我试着在去college.So之前自学,这是我的简单程序,
public class Lesson_16_1 {
public static void main(String[] args) {
int counter;
for(counter = 5; counter <= 20; counter=counter+2);
System.out.println("the counter is at " + counter);
}
}期望变量应该是5,7,9,11,13,15,17,19.
相反,我得到的输出是“计数器在21”
我不明白为什么值会出现21,尽管我清楚地说明了条件<=20.Please尽快回复我的possible.Thanks百万。
发布于 2015-04-30 11:02:49
你有分号,“停止”循环做任何其他事情。
所以改变这个
for(counter = 5; counter <= 20; counter=counter+2);到这个
for(counter = 5; counter <= 20; counter=counter+2)还有一个好建议
public static void main(String[] args) {
int counter;
for(counter = 5; counter <= 20; counter=counter+2){
System.out.println("the counter is at " + counter);
}
}发布于 2015-04-30 11:03:17
您的for loop没有一个主体(迭代时不需要执行)
for(counter = 5; counter <= 20; counter=counter+2); // it is ending here您需要将代码更改为下面的代码,以获得所期望的结果。
for(counter = 5; counter <= 20; counter=counter+2){
System.out.println("the counter is at " + counter);
}发布于 2015-04-30 11:21:06
您在for语句的末尾使用了分号,如下所示:
for(counter = 5; counter <= 20; counter=counter+2);编写for循环的语法如下,
for(initialization ; condition ; step ){
//repeatable task here
}在这里,step可以像incrementing、循环变量(在您的例子中是counter)或decrementing。如果您的可重复任务是单个语句(这就是您的情况),那么您可以编写不带大括号的for循环,如下所示,
for(counter = 5; counter <= 20; counter=counter+2)
System.out.println("the counter is at " + counter);但正如我所提到的,它只适用于一项声明。
https://stackoverflow.com/questions/29966001
复制相似问题