2014-01-19 52 views
0

我只是試圖從控制檯讀取整數(用空格分隔,例如:「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(); 
     } 
+0

http://stackoverflow.com/questions/5071458/keep-reading-numbers-until-newline-reached-using-a-scanner – nmclean

回答

0

使用nextLine()

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