更新时间:2023-11-10 14:19:34
使用 Scanner.nextInt()
时,输入应为整数.输入其他任何内容(包括实数)都会引发 InputMismatchException
.为了确保无效输入不会停止您的程序,请使用try/catch处理异常:
When you're using Scanner.nextInt()
the input is expected to be an integer. Inputting anything else, including a real number, will throw an InputMismatchException
. To make sure invalid input doesn't stop your program, use a try/catch to handle the exception:
int num;
try {
num = sc.nextInt();
// Continue doing things with num
} catch (InputMismatchException e) {
// Tell the user the error occured
}