我正在尝试编写一个程序,提示用户读取两个整数并显示它们的总和,如果输入不正确,我的程序应该提示用户再次读取该数字。这就是我想出来的:
import java.util.*;
public class NumFormatException {
public static void main(String[] args) throws NumberFormatException {
Scanner input=new Scanner(System.in);
System.out.println("Enter 2 integers: ");
int num1=0;
int num2=0;
boolean isValid = false;
while (!isValid) {
try
{
num1=input.nextInt();
num2=input.nextInt();
isValid=true;
}
catch(NumberFormatException ex)
{
System.out.println("Invalid input");
}
}
System.out.println(num1 + " + " + num2 + " = " + (num1 + num2));
}
}
如果输入不正确,我的主要目标是让用户处于重新输入整数的情况。当我输入两个整数时,操作运行良好,但我的问题是例外:当我输入例如 a 而不是整数时,我的程序崩溃了。
答案 0 :(得分:2)
这里有两个问题。首先,如果nextXYZ
Scanner
方法遇到错误输入,则不会抛出NumberFormatException
而是InputMismatchException
。其次,如果抛出这样的异常,则不会消耗输入令牌,因此您需要再次显式使用它:
try {
num1=input.nextInt();
num2=input.nextInt();
isValid=true;
} catch (InputMismatchException ex) { // catch the right exception
System.out.println("Invalid input");
// consume the previous, erroneous, input token(s)
input.nextLine();
}