带扫描仪输入的Java无限循环

问题描述

当我在循环外初始化扫描器对象时,如果给出无效输入(即,非int输入)的代码进入catch块,则会出现无限循环。我认为这与保留该输入的Scanner对象有关,但是我不确定为什么会这样。

这是我的代码

public class Random {
public static void main(String[] args) {
    Scanner scan = new Scanner(system.in);
    int age = 13;
    int guess = 0;
    do {
        System.out.print("guess age: ");
        try{
            guess = scan.nextInt();
        }
        catch (InputMismatchException i){
            System.out.println("incorrect input");
        }
        if(guess!=age) System.out.println("try again");
        else System.out.println("well done");
    }while(guess!=age);
}}

将扫描对象初始化带入try块可解决此问题:

public class Random {
public static void main(String[] args) {
    
    int age = 13;
    int guess = 0;
    do {
        System.out.print("guess age: ");
        try{
            Scanner scan = new Scanner(system.in);
            guess = scan.nextInt();
        }
        catch (InputMismatchException i){
            System.out.println("incorrect input");
        }
        if(guess!=age) System.out.println("try again");
        else System.out.println("well done");
    }while(guess!=age);
}

}

为什么会这样,为什么在输入整数值的正常情况下不会发生这种情况。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)