2015-08-28 23 views
0

昨天晚上我開始做CodeAbbey問題,他們提到使用stdIn,因爲一些輸入數據很長,所以複製/粘貼比手工更容易。我之前從未使用過掃描儀,所以看起來很簡單。我得到了它的單線路輸入工作的話,我有一個問題,當輸入爲:掃描儀nextLine,陷入while循環或奇數時間退出

867955 303061 
977729 180367 
844485 843725 
393481 604154 
399571 278744 
723807 596408 
142116 475355 

我認爲nextLine會讀每對夫婦,XXXX YYYYY。我把代碼放在一個while循環中,基於nextLine是否爲空。它運行,但我得到奇怪的輸出,只有在我幾次回擊。

package com.secryption; 

import java.util.Scanner; 


public class Main { 

    public static void main(String[] args) { 

     System.out.println("Input: "); 
     Scanner scanner = new Scanner(System.in); 
     String input = ""; 


     while(!(scanner.nextLine().isEmpty())) { 
      input = input + scanner.nextLine(); 
     } 
     String[] resultSet = input.split("\\s+"); 

     for(String s : resultSet) { 
      System.out.println(s); 
     } 


    } 

} 

我想我可能需要添加scanner.nextLine()輸入後需要的東西。我嘗試了一個空間,但沒有幫助。我嘗試了一個換行符,但並沒有讓它變得更好。

這個「應該」把所有的數字放在一個數組中,沒什麼特別的。掃描儀丟失了什麼?

編輯:好的@Luiggi門多薩是正確的。我發現這個How to terminate Scanner when input is complete?的帖子。所以基本上它工作,我只是希望它做些什麼。

+0

您需要'while(scanner.hasNextLine())'。 –

+0

@ PM77-1我試過了。有了這些,我可以得到一些數字,然後重複一遍「Next Line:」。它永遠不會退出。 – TheEditor

回答

1

的問題是在這裏:

while(!(scanner.nextLine().isEmpty())) { 
    input = input + scanner.nextLine(); 
} 

Scanner#nextLine讀取線,並會繼續讀書。你正在讀兩行,而不是存儲第一行讀取的結果,只是讀取和存儲第二行的結果。

只要改變上述代碼到:

StringBuilder sb = new StringBuilder(); 
while(scanner.hasNextLine()) { 
    sb.append(scanner.nextLine()).append(" "); 
} 
+0

輸出正確的數據,但只有在我停止它之後。這並不意味着它仍然只是坐在那裏while循環? – TheEditor

0

hasNext()是一個通過對按壓輸入將不發送權的窗口在Mac牛和控制Ž結合鍵控制d終止文件指示器的端消息 到JVM