我已经读取了只能是 int 类型的用户输入,当用户输入字母而不是 int 时就会出现问题。我知道如何处理异常,但我想返回扫描仪读取用户犯错误的地方。我能怎么做? 我已经尝试过无限循环,但它不起作用。
try{
System.out.print("enter number: ");
value = scanner.nextInt();
}catch(InputMismatchException e){
System.err.println("enter a number!");
}
最佳答案
虽然其他答案为您提供了使用循环的正确想法,但您应该避免使用异常作为基本逻辑的一部分。相反,您可以使用 Scanner
中的 hasNextInt
来检查用户是否传递了整数。
System.out.print("enter number: ");
while (!scanner.hasNextInt()) {
scanner.nextLine();// consume incorrect values from entire line
//or
//tastiera.next(); //consume only one invalid token
System.out.print("enter number!: ");
}
// here we are sure that user passed integer
int value = scanner.nextInt();
关于java - 用户错误后返回扫描仪读取 - java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22732307/