import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("\nThe sum of the numbers is: " + getSumOfInput());
}
public static int getSumOfInput () {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
boolean checkValidity = userInput.hasNextInt();
if(checkValidity) {
int userNum = userInput.nextInt();
userInput.nextLine();
System.out.println("Number " + userNum + " added to the total sum.");
sumOfNums += userNum;
counter++;
} else {
System.out.println("Invalid input. Please, enter a number.");
}
}
userInput.close();
return sumOfNums;
}
}
大家好!
我刚刚开始使用 Java 并且了解了控制流,现在我转向了用户输入,所以我了解的不多。问题是这段代码。如果您在我测试时输入有效输入,则工作正常,无需担心。问题是我想检查用户的错误输入,例如当他们输入像“asdew”这样的字符串时。我想显示 else 语句中的错误并继续向用户询问另一个输入,但在这样的输入之后,程序将进入无限循环,显示“输入数字 X:无效输入。请输入一个数字.”。
你能告诉我有什么问题吗?请注意,我对 Java 可以提供的功能知之甚少,因此您的解决方案范围有点有限。
答案 0 :(得分:0)
问题是,一旦您输入不能解释为 int
的输入,userInput.hasNextInt()
将返回 false(如预期)。但是这个调用不会清除输入,所以对于每次循环迭代,条件都不会改变。所以你会得到一个无限循环。
如果可以使用 nextInt() 方法将此扫描器输入中的下一个标记解释为默认基数中的 int 值,则返回 true。扫描仪不会通过任何输入。
解决方法是在遇到无效输入时清除输入。例如:
} else {
System.out.println("Invalid input. Please, enter a number.");
userInput.nextLine();
}
您可以采用的另一种方法,它需要较少的扫描器输入读取,是始终采用下一行,然后在解析时处理不正确的输入。
public static int getSumOfInput() {
int counter = 0;
int sumOfNums = 0;
Scanner userInput = new Scanner(System.in);
while (counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
String input = userInput.nextLine();
try {
int convertedInput = Integer.parseInt(input);
System.out.println("Number " + convertedInput + " added to the total sum.");
sumOfNums += convertedInput;
counter++;
} catch (NumberFormatException e) {
System.out.println("Invalid input. Please, enter a number.");
}
}
return sumOfNums;
}
答案 1 :(得分:0)
在 userInput.nextLine();
之后调用 while
:
...
while(counter <= 10) {
System.out.print("Enter the number " + counter + ": ");
userInput.nextLine();
...