【问题标题】:debugging(eclipse) using for loop cannot get an expected answer使用 for 循环调试(eclipse)无法得到预期的答案
【发布时间】:2015-04-30 11:02:02
【问题描述】:

我是java初学者,想在上大学之前自学。所以这是我的简单程序,

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,尽管我清楚地说明了条件

【问题讨论】:

    标签: java android debugging logic


    【解决方案1】:

    你有分号,它“停止” for-cycle 做任何其他事情

    所以改变这个

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

        您在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);
        

        但正如我所提到的,它仅适用于单个语句。

        【讨论】:

          猜你喜欢
          • 2022-11-25
          • 1970-01-01
          • 1970-01-01
          • 2018-01-26
          • 1970-01-01
          • 1970-01-01
          • 2020-08-13
          • 2021-04-13
          • 1970-01-01
          相关资源
          最近更新 更多