我是 Java 新手,我想继续请求用户输入,直到用户输入整数,这样就不会出现 InputMismatchException。我已经尝试过这段代码,但当我输入非整数值时仍然出现异常。
int getInt(String prompt){
System.out.print(prompt);
Scanner sc = new Scanner(System.in);
while(!sc.hasNextInt()){
System.out.println("Enter a whole number.");
sc.nextInt();
}
return sc.nextInt();
}
感谢您的宝贵时间!
最佳答案
使用 next
而不是 nextInt
获取输入。放置一个 try catch 以使用 parseInt 方法解析输入。如果解析成功则中断 while 循环,否则继续。
试试这个:
System.out.print("input");
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("Enter a whole number.");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
System.out.println("Correct input, exit");
break;
} catch (NumberFormatException ne) {
System.out.println("Input is not a number, continue");
}
}
关于java - 如何循环用户输入直到输入整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38974719/