2011-10-05 73 views
5

我在做一個學校的練習,我不知道如何做一件事。 對於我讀過的,掃描儀不是最好的方法,但由於老師只使用掃描儀,這必須使用掃描儀完成。空行後Java停止閱讀

這是問題所在。 用戶將輸入文本到一個數組。該數組最多可以有10行,用戶輸入以空行結束。

我已經做到了這一點:

String[] text = new String[11] 
Scanner sc = new Scanner(System.in); 
int i = 0; 
System.out.println("Please insert text:"); 
while (!sc.nextLine().equals("")){ 
     text[i] = sc.nextLine(); 
     i++;   
    } 

但這不能正常工作,我無法弄清楚。 理想的情況下,如果用戶輸入:

This is line one 
This is line two 

,現在按enter鍵,文打印陣列也應該給:

[This is line one, This is line two, null,null,null,null,null,null,null,null,null] 

你能幫助我嗎?

回答

8
while (!sc.nextLine().equals("")){ 
     text[i] = sc.nextLine(); 
     i++;   
} 

它從輸入中讀取兩行:一個與空字符串比較,另一個實際存儲在數組中。你想放線的變量,以便您檢查,並用相同的String在兩種情況處理:

while(true) { 
    String nextLine = sc.nextLine(); 
    if (nextLine.equals("")) { 
     break; 
    } 
    text[i] = nextLine; 
    i++; 
} 
+0

許多謝謝你的解釋。該工作 – Favolas

+1

不要忘記你的休息時間10行的最大輸入。 –

+0

@XenoLupus是的。我沒有忘記,但非常感謝 – Favolas

1

這裏是典型的readline成語,應用到你的代碼:

String[] text = new String[11] 
Scanner sc = new Scanner(System.in); 
int i = 0; 
String line; 
System.out.println("Please insert text:"); 
while (!(line = sc.nextLine()).equals("")){ 
    text[i] = line; 
    i++;   
}