如果我的程序中允许的输入只是int
类型,但是用户可以任意键入一个不允许的类型字符,例如double
或char
等。我如何处理那?我确信有Throw exception
类似的东西,但我不确定它是如何完成的。任何建议将不胜感激
//here is my code
System.out.print("Too " +additionalInfo+ "! Try again: ");
attemptCounter++;
int x= input.nextInt(); // here is where i want the usr to type in their input
答案 0 :(得分:0)
使用循环在无效输入后再次提示用户输入,例如
int userInput;
while(true) {
try {
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
userInput = input.nextInt();
break;
}
catch(InputMismatchException | NumberFormatException ex ) {
System.out.println("Invalid Number, Please try again");
}
}