扫描器nextInt()和hasNextInt()问题 [英] Scanner nextInt() and hasNextInt() problems

查看:558
本文介绍了扫描器nextInt()和hasNextInt()问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究为什么scan.nextInt()会消耗第二次迭代之前的整数。任何人都可以理解正在发生的事情并解释扫描仪没有超过任何输入意味着什么?

I'm investigating why scan.nextInt() consumes the previous integer from the second iteration onwards. Can anyone make sense of what's going on and also explain what "The scanner does not advance past any input" means exactly?

请忽略无限循环。它仅用于测试目的。

Please ignore the infinite loop. It's only for testing purposes.

示例:

输入新数据:0

0

输入的数据

再次输入数据:1

执行数据

输入新数据:1< - 此值自动输入(取自先前输入)

数据输入

再次输入数据:

Example:
Enter new data: 0
0
data entered
Enter data again: 1
executed
Enter new data: 1 <- this value is automatically entered (taken from previous input)
data entered
Enter data again:

    while(true)
    {
        System.out.print("Enter new data: ");
        System.out.println(scan.nextInt());
        //scan.nextLine();    //must include but I'm not sure why 
        System.out.println("data entered");
        System.out.print("Enter data again: ");
        if(scan.hasNextInt())
        {
            System.out.println("executed");
            //scan.nextLine();    //must include this too but not sure why
        }
    }


推荐答案

一般模式如下:

while(scan.hasNextInt())
{
    System.out.println(scan.nextInt());
}

首先你要确保有下一个int,如果有下一个你用它做点什么。你正在以其他方式做到这一点。首先你消耗它,而不是检查是否有另一个,这是错误的。

First you make sure that there is next int and if there is next one you do something with it. You are doing it other way round. First you consume it, than you check whether there is another one, which is wrong.

为什么我们应该在nextXXX之前调用hasNextXXX?因为如果没有这样的下一个令牌,nextXXX可以抛出NoSuchElementException。看看这个例子:

Why should we call hasNextXXX before nextXXX ? Because nextXXX can throw NoSuchElementException if there isn't such next token. Look at this example :

String str = "hello world";
Scanner scan = new Scanner(str);

此字符串中没有整数,这意味着

There is no integer in this string, which means that

System.out.println(scan.nextInt());

将抛出NoSuchElementException。但是如果你使用我写的while循环,你首先检查输入中是否有一个Integer,然后再尝试用它做任何事情。因此,这是标准模式,而不是处理不必要的异常。

will throw NoSuchElementException. But if you use the while loop that I wrote you first check that there is an Integer in the input before you try doing anything with it. Therefore this is the standard pattern instead of handling unnecessary exceptions.

这篇关于扫描器nextInt()和hasNextInt()问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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