扫描仪永不停止读取输入 [英] Scanner never stops reading input

查看:67
本文介绍了扫描仪永不停止读取输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想从控制台读取整数(用空格隔开,例如:"6 9 20"),然后将它们传输到数组中以备后用.但是,使用我当前编写的代码,我的扫描仪对象永远不会停止读取我的输入.我觉得扫描器对象根本不知道确切什么时候停止输入,但是我希望它在按下Enter键后立即停止读取.我已经在这个网站上广泛搜索了准确的答案,但无济于事.

I'm simply trying to read integers (separated by spaces, such as : "6 9 20") from the console and transferring them into an array for later use. However, with the code I currently have written, my scanner object never stops reading my input. I feel like the scanner object simply doesn't know exactly when to stop taking input, but I'd like it to stop reading as soon as I hit Enter. I've searched this website extensively for a precise answer, but to no avail.

这是我的代码:

        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();
        }

推荐答案

使用nextLine().

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

这篇关于扫描仪永不停止读取输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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