*12.2(InputMismatchException异常)编写一个程序,提示用户读取两个整数,然后显示他们的和。程序应该在输入不正确时提示用户在此读取数值。 *12.2(Inputmismatch exception)Write a program that prompts the user to read two integers and then displays their sum. The program should prompt the user to read the value here when the input is incorrect.
参考代码:
package chapter12;import java.util.InputMismatchException;import java.util.Scanner;publicclassCode_02{publicstaticvoidmain(String[] args){
Scanner input =newScanner(System.in);boolean continueInput =true;do{try{
System.out.print("Enter two integer: ");int number1 = input.nextInt();int number2 = input.nextInt();
System.out.println("The nmumber enter is "+ number1 +" "+ number2);
continueInput =false;}catch(InputMismatchException ex){
System.out.println("Try again.("+"Incorrect input:an integer is required)");
input.nextLine();}}while(continueInput);}}
结果显示:
Enter two integer: ss er
Try again.(Incorrect input:an integer is required)
Enter two integer:25
The nmumber enter is 25
Process finished with exit code 0