Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 第二个catch在while循环中继续执行(Try catch)_Java_Try Catch - Fatal编程技术网

Java 第二个catch在while循环中继续执行(Try catch)

Java 第二个catch在while循环中继续执行(Try catch),java,try-catch,Java,Try Catch,我怎样才能解决它 为什么第二个catch一直在输出控制台中打印 我只是想打印一次,如果布尔数据类型不是真的,那么再次返回循环 Scanner input=new Scanner(System.in); int a ,b,result; boolean status=false; while(!status){ try{ a=input.nextInt(); b=input.nextInt(); resu

我怎样才能解决它

为什么第二个catch一直在输出控制台中打印

我只是想打印一次,如果布尔数据类型不是真的,那么再次返回循环

    Scanner input=new Scanner(System.in);

    int a ,b,result;
    boolean status=false;
    while(!status){
    try{

        a=input.nextInt();
        b=input.nextInt();

        result=a/b;
        status=true;

    }catch (ArithmeticException ex){

        System.out.println(ex.getMessage());

    }catch(InputMismatchException ex){

        System.out.println(ex);

    }catch(Exception ex){

        System.out.println(ex.getMessage());

    }
    }

}

请检查我的在线评论

while(!status){
    try{

        a=input.nextInt();
        b=input.nextInt();

        result=a/b;
        status=true;

    }catch (ArithmeticException ex){

        System.out.println(ex.getMessage());

    }catch(InputMismatchException ex){

        System.out.println(ex);
        input.next(); // So when ever InputMismatchException occurs Scanner will not consume the token it will keep that token so we need to consume that by using `next()`
    }catch(Exception ex){

        System.out.println(ex.getMessage());

    }

在catch块中添加break语句,您可以使用它来获取所有不匹配的输入

catch(InputMismatchException ex){
            ex.printStackTrace();
            System.out.println(ex.getMessage());
            break;
        }

您必须使用非
int
的输入。在
catch
块中添加
input.nextLine()
。@ElliottFrisch这不是一个答案吗?请注意,这会更好,因为他需要无限时间从扫描仪获取输入,但在您的代码中,在您给出有效输入后,它会一直退出。。。循环仍然存在。我假设他试图从用户那里获得无限时间的输入