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

查看:19
本文介绍了使用 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.

顺便说一句,为了使您的代码更简洁并避免诸如创建异常之类的昂贵操作,您应该使用诸如 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天全站免登陆