首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用for循环进行调试(Eclipse)不能得到预期的答案

使用for循环进行调试(Eclipse)不能得到预期的答案
EN

Stack Overflow用户
提问于 2015-04-30 11:02:02
回答 3查看 38关注 0票数 0

我是java的初学者,我试着在去college.So之前自学,这是我的简单程序,

代码语言:javascript
复制
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百万。

EN

回答 3

Stack Overflow用户

发布于 2015-04-30 11:02:49

你有分号,“停止”循环做任何其他事情。

所以改变这个

代码语言:javascript
复制
 for(counter = 5; counter <= 20; counter=counter+2);

到这个

代码语言:javascript
复制
 for(counter = 5; counter <= 20; counter=counter+2)

还有一个好建议

代码语言:javascript
复制
public static void main(String[] args) {
    int counter;

    for(counter = 5; counter <= 20; counter=counter+2){
        System.out.println("the counter is at "  + counter);
    }
}
票数 1
EN

Stack Overflow用户

发布于 2015-04-30 11:03:17

您的for loop没有一个主体(迭代时不需要执行)

代码语言:javascript
复制
for(counter = 5; counter <= 20; counter=counter+2); // it is ending here

您需要将代码更改为下面的代码,以获得所期望的结果。

代码语言:javascript
复制
 for(counter = 5; counter <= 20; counter=counter+2){
    System.out.println("the counter is at "  + counter);
 }
票数 1
EN

Stack Overflow用户

发布于 2015-04-30 11:21:06

您在for语句的末尾使用了分号,如下所示:

代码语言:javascript
复制
for(counter = 5; counter <= 20; counter=counter+2);

编写for循环的语法如下,

代码语言:javascript
复制
for(initialization ; condition ; step ){

//repeatable task here 
}

在这里,step可以像incrementing、循环变量(在您的例子中是counter)或decrementing。如果您的可重复任务是单个语句(这就是您的情况),那么您可以编写不带大括号的for循环,如下所示,

代码语言:javascript
复制
for(counter = 5; counter <= 20; counter=counter+2)
    System.out.println("the counter is at "  + counter);

但正如我所提到的,它只适用于一项声明。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29966001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档