扫描器使用nextInt()不断跳过输入信息并循环 [英] Scanner keeps skipping input whist using nextInt() and loops

查看:99
本文介绍了扫描器使用nextInt()不断跳过输入信息并循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用while循环来确保输入到扫描仪对象的值是这样的整数:

I am using a while loop to make sure that the value entered to a scanner object is an integer as such:

while (!capacityCheck) {
        try {
            System.out.println("Capacity");
            capacity = scan.nextInt();
            capacityCheck = true;
        } catch (InputMismatchException e) {
            System.out.println("Capacity must be an integer");
        }
    }

但是,如果用户没有输入整数,则当它返回并接受另一个输入时,它只会重复打印"Capacity",然后在catch中输出,而无需输入更多内容.我该如何停止?

however, if the user does not enter an integer, when it should go back and take another input it just repeatedly prints "Capacity" followed by the output in the catch without asking for more input. How do I stop this?

推荐答案

scan.nextLine();

将这段代码放入catch块中,以消耗非整数字符以及保留在缓冲区中的换行符(因此,无限打印catch sysout),如果您已经输入错误.

Put this piece of code inside your catch block, to consume the non integer character along with the new line character which is stays in the buffer(hence, infinitely printing the catch sysout), in the case where you've given a wrong input.

当然,还有其他更清洁的方法可以实现所需的功能,但是我想这需要在代码中进行一些重构.

Ofcourse, there are other cleaner ways to achieve what you want, but I guess that will require some refactoring in your code.

这篇关于扫描器使用nextInt()不断跳过输入信息并循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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