【发布时间】: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