【问题标题】:Infinite loop when trying to decrement i inside a for loop尝试在 for 循环中减少 i 时的无限循环
【发布时间】:2017-08-07 11:41:10
【问题描述】:

我有一个计数控制循环,用于添加用户输入的一系列 5 个数字。我在其中有一个决策结构,旨在拒绝任何奇数或负数,但将任何偶数正数添加到累加器中。为此,我告诉程序如果输入了奇数或负数,则将 i 减 1,以便循环仍然接受 5 个正偶数。相反,它最终接受了无限数量的数字(即陷入无限循环)。有人可以解释为什么这不起作用/为什么它在我身上无限循环吗?

这是我的代码:

public static double numberRun(){
//variable to store user input
String userNumString = "null";
int userNum = 0;
//variable to store total of all user inputted numbers
double accumulator = 0;
//setting up function to read inputs
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);   
//count for 5 loops
for(int i=1; i<=5; i++) {
//if the total of the numbers entered so far is < 100, accept more numbers -
- doesnt affect initial number because accumulator is initialized to 0
if (accumulator < 100) {
System.out.println("Please enter a number");
//count controlled loop to ensure no more than 5 numbers are entered
 try {
  userNumString = reader.readLine();
  userNum = Integer.parseInt(userNumString);
    System.out.println(userNum);
      } catch (Exception e){
  System.out.println("Error reading from user");
}
  //reject odd or negative numbers, if a number is rejected set counter 
  back 1 to ensure 5 valid numbers total are inputted
    if (0 <= userNum) {
      if ((userNum % 2) == 0) {
        accumulator = accumulator+userNum;
      } else
        System.out.println("I'm sorry, odd numbers are not allowed");
          i=i-1;
    } else if (userNum < 0) {
         System.out.println("I'm sorry, negative numbers are not allowed");
         i=i-1;
           }
    //when the total of all user inputted numbers is ≥ 100, stop the count 
    controlled loop (stop accepting numbers)
  } else if (accumulator >= 100) {
     i=5;
  }
   }
  //return the total for the run
  return accumulator;

}

【问题讨论】:

  • 在 if 条件下会 0>= userNum 而不是 0
  • 我同意@Thilo 的回答,您需要检查 IF 和 ELSE 的上下文;顺便重新缩进你的代码。

标签: java


【解决方案1】:
} else
  System.out.println("I'm sorry, odd numbers are not allowed");
  i=i-1;

i=i-1 不是else 的一部分。每次都会执行。

  1. 使用代码格式化程序
  2. 始终使用{},切勿裸露ifelseforwhile

【讨论】:

  • 就是这样!谢谢!我正在使用 Dr. Java,所以它告诉我大括号中包含的内容(不确定这是否与代码格式化程序相同,我对此很陌生)。不知道我是怎么错过的,但我必须更加小心地将 {} 与我的 else 语句一起使用!另外,i=--i 会和 i=(i-1) 做同样的事情,对吧?我对 i-- vs --i 和 i++ vs ++i 有点困惑
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 1970-01-01
  • 1970-01-01
  • 2011-12-22
相关资源
最近更新 更多