尝试在for循环中递减i时的无限循环

时间:2017-08-07 03:37:43

标签: java

我有一个计数控制循环,用于添加用户输入的一系列5个数字。我内部有一个决策结构,用于拒绝任何奇数或负数,但是将任何偶数正数加到累加器中。为此,我告诉程序如果输入奇数或负数,则减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;

}

1 个答案:

答案 0 :(得分:2)

} else
  System.out.println("I'm sorry, odd numbers are not allowed");
  i=i-1;

i=i-1不属于else。它每次执行。

  1. 使用代码格式化程序
  2. 始终使用{},永不使用ifelseforwhile