使用try-catch和while循环捕获时出错 [英] Error catching with try-catch and while loop

查看:122
本文介绍了使用try-catch和while循环捕获时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确保用户输入是一个整数但是当我使用下面的代码时,我只得到 print 语句的无限循环。关于如何改进的任何建议?

I'm trying to make sure that the users input is an integer but when I use the below code I just get an infinite loop of the print statement. Any advice of how to improve?

boolean valid = false;
System.out.println("What block are you gathering? (use minecraft block ids)");
while(valid == false){
    try{
        block = input.nextInt();
        valid = true;
    }
    catch(InputMismatchException exception){
        System.out.println("What block are you gathering? (use minecraft block ids)");
        valid = false;
    }
}


推荐答案

nextInt()不消耗无效输入,因此它会一遍又一遍地尝试读取相同的无效值。要解决此问题,您需要通过调用 next() nextLine()来显式使用它,它接受任何值。

nextInt() doesn't consume invalid input so it will try read same invalid value over and over again. To solve this problem you need to consume it explicitly by calling next() or nextLine() which accept any value.

BTW使您的代码更清晰并避免昂贵的操作,如创建异常,您应该使用 hasNextInt()等方法。

BTW to make your code cleaner and avoid expensive operations like creating exceptions you should use methods like hasNextInt() .

以下是组织代码的方法

System.out.println("What block are you gathering? (use minecraft block ids)");
while(!input.hasNextInt()){
    input.nextLine();// consume invalid values until end of line, 
                     // use next() if you want to consume them one by one.
    System.out.println("That is not integer. Please try again");
}
//here we are sure that next element will be int, so lets read it
block = input.nextInt();

这篇关于使用try-catch和while循环捕获时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆