利用异常+nextLine()解决输入不匹配的问题

/**
* 利用异常+nextLine()解决输入不匹配的问题
*/

package java_eight;

import java.util.InputMismatchException;
import java.util.Scanner;

public class InputMismatchExceptionDemo {

public static void main(String[] args) {
    Scanner input=new Scanner(System.in);
    boolean continueInput=true;
    do{
        try{
            System.out.print("Enter two integers:");
            int number1=input.nextInt();
            int number2=input.nextInt();
            System.out.println("The sum is "+(number1+number2));
            continueInput=false;
        }catch(InputMismatchException ex){
            System.out.println("Try again:(Incorrect input:two integers are required)");

            /**
             * 此处的input.nextLine();是本程序的亮点,如果没有input.nextLine();
             * 当输入的两个数值不是整数时,程序将会抛出异常,此时程序将会是死循环一直运行如下:
             * Enter two integers:Try again:(Incorrect input:two integers are required)
             * Enter two integers:Try again:(Incorrect input:two integers are required)
             * Enter two integers:Try again:(Incorrect input:two integers are required)
             * 原因是如果number1或者number2不是整数时,将会抛出异常,当第二次执行程序时,
             * 由于第一次输入的非整数的数值没有被读取,input.nextInt()会继续读取,结果会一直发生异常,
             * 故而continueInput=false;语句永远执行不到,出现死循环;
             * 
             * 如果使用input.nextLine();语句,即使number1或者number2在某次输入中不是整数,
             * input.nextLine();语句会读取回车符前面没有被读取的非整数而不输出,一次来保证程序正确
             * 执行。
             * 
             */

            input.nextLine();

        }

    }while(continueInput);




}

}

猜你喜欢

转载自blog.csdn.net/qq_38986609/article/details/78598260