欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

第十二章第二题(InputMismatchException异常)(Inputmismatch exception)

程序员文章站 2022-07-14 20:11:25
...

第十二章第二题(InputMismatchException异常)(Inputmismatch exception)

  • *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;

public class Code_02 {
    public static void main(String[] args) {
        Scanner input = new Scanner(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: 2  5
The nmumber enter is 2 5

Process finished with exit code 0