【问题标题】:Scanner nextInt() and hasNextInt() problems扫描仪 nextInt() 和 hasNextInt() 问题
【发布时间】:2013-12-26 21:02:16
【问题描述】:

我正在调查为什么 scan.nextInt() 从第二次迭代开始消耗前一个整数。任何人都可以理解正在发生的事情并解释“扫描仪不会超过任何输入”的确切含义吗?

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

示例:
输入新数据:0
0
输入数据
再次输入数据:1
执行
输入新数据:1 输入数据
再次输入数据:

    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
        }
    }

【问题讨论】:

  • 解释运行此代码时会发生什么,以及您希望看到什么? “[it] 从第二次迭代开始消耗前一个整数”我不清楚。
  • 您似乎没有在示例代码中的任何地方调用nextInt(),但它在您的问题标题中;我错过了什么吗?
  • 第 4 行,@DavidNorris - System.out.println(scan.nextInt());
  • 确实我错过了一些东西;)谢谢。

标签: java int


【解决方案1】:

一般模式是这样的:

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

首先你确保有下一个 int,如果有下一个你用它做点什么。你正在做相反的事情。首先你消费它,然后你检查是否有另一个,这是错误的。

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

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

这个字符串中没有整数,也就是说

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

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

【讨论】:

猜你喜欢
  • 2014-06-04
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多