【问题标题】:Scanner never stops reading input扫描仪永远不会停止读取输入
【发布时间】:2014-01-19 00:18:51
【问题描述】:

我只是试图从控制台读取整数(以空格分隔,例如:“6 9 20”)并将它们传输到数组中以供以后使用。但是,使用我目前编写的代码,我的扫描仪对象永远不会停止读取我的输入。我觉得扫描仪对象根本不知道何时停止输入,但我希望它在我按下 Enter 后立即停止读取。我在这个网站上广泛搜索了一个准确的答案,但无济于事。

这是我的代码:

        int[] mcNug = new int[5];

        Scanner scanner = new Scanner(System.in);
        List list = new ArrayList<Integer>();
        int i = 0;
        while(scanner.hasNextInt() && scanner.hasNext())
        {
          list.add(scanner.nextInt());
          mcNug[i] = (int) list.get(i);
          i++;
          scanner.next();
        }

【问题讨论】:

标签: java.util.scanner


【解决方案1】:

使用nextLine()

while( scanner.hasNextLine() ){
  String line = scanner.nextLine();
  String[] numbers = line.split("\\s+");
  ... do something with numbers array ..
}

【讨论】:

    猜你喜欢
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-07
    相关资源
    最近更新 更多