*12.2 (InputMismatchException) Write a program that prompts the user to read
two integers and displays their sum. Your program should prompt the user to
read the number again if the input is incorrect.
*12.2(InputMismatchException异常)编写一个程序,提示用户读取两个整数,然后显示他们的和。程序应该在输入不正确时提示用户在此读取数值。
代码如下:
import java.util.*;
public class Unite12Test2
{
public static void main(String[] args)
{
boolean p = true;
Scanner input = new Scanner(System.in);
do {
try {
System.out.println("请输入两个整数: ");
int num1 = input.nextInt();
int num2 = input.nextInt();
System.out.println(num1+num2);
p = false;
} catch (Exception e) {
// TODO 自动生成的 catch 块
System.out.println("你输入的数字错误,请重新输入");
input.nextLine();
}
}while(p);
}
}
结果如下: