如何安全扫描整数输入? [英] How Do I Safely Scan for Integer Input?

查看:192
本文介绍了如何安全扫描整数输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Scanner scanner = new Scanner();
int number = 1;

do
{
    try
    {
        option = scanner.nextInt();
    }
    catch (InputMismatchException exception)
    {
        System.out.println("Integers only, please.");
    }
}
while (number != 0);

尽管异常处理,当非整数输入给出时,此代码将进入无限循环。而不是 Scanner 暂停在下一次迭代中收集输入,它只是继续抛出$ code> InputMismatchException 直到程序被杀死。

Despite the exception handling, this code will enter an infinite loop when non-integer input is given. Instead of Scanner pausing to collect input in the next iteration, it simply continues throwing InputMismatchExceptions until the program is killed.

扫描整数(或另一种类型,我想)输入,丢弃无效输入并正常继续循环的最佳方式是什么?

What's the best way to scan for integer (or another type, I suppose) input, discarding invalid input and continuing the loop normally?

推荐答案

在尝试将输入的值分配给int之前,您应该检查输入是否可以解析为int。您不应该使用异常来确定输入是否正确,这是不好的做法,应该避免。

You should check whether or not the input can be parsed as an int before attempting to assign the input's value to an int. You should not be using an exception to determine whether or not the input is correct it is bad practice and should be avoided.

if(scanner.hasNextInt()){
   option = scanner.nextInt();
}else{
   System.out.printLn("your message");
}

这样可以检查输入是否可以解释为int如果是这样分配值,如果不显示消息。调用该方法不会推进扫描仪。

This way you can check whether or not the input can be interpreted as an int and if so assign the value and if not display a message. Calling that method does not advance the scanner.

这篇关于如何安全扫描整数输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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