Scanner never stops reading input

不打扰是莪最后的温柔 提交于 2019-12-11 18:21:43

问题


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.

Here is my code:

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

回答1:


use a nextLine().

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


来源:https://stackoverflow.com/questions/21211634/scanner-never-stops-reading-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!