2016-07-22 294 views
-2

我有一個關於從java控制檯讀取字符串的問題。當我給每行輸入單詞時,直到用「停止」停止,所有這些單詞都應該存儲在一個字符串數組中。Java控制檯逐行讀取輸入並存儲在字符串數組中

我的投入將是:

蘋果
芒果
葡萄
停止----->上停止字符串結尾這裏

所有3個水果名稱將被存儲在temp

但是,當我輸入一個單詞並想通過單擊Enter鍵輸入另一行時,它會打印輸出。

我該如何修改?

Scanner scanner=new Scanner(System.in); 
System.out.println("Enter the words"); 
String temp=scanner.nextLine(); 
+0

雕像:) 放scanner.nextLine()成while循環和出口僅像okstop您所選擇的特定詞:) – amitmah

+1

請發表[ mcve]你描述的行爲。 –

回答

1

你的問題是,你正在從控制檯讀取一行並打印它。

你應該做的是繼續閱讀直到「停止」,這可以通過一個while循環完成。

此代碼應爲你工作得好:

Scanner scanner = new Scanner(System.in); 
System.out.println("Enter the words"); 
String input = scanner.nextLine(); // variable to store every input line 
String fruits = "";  // this should store all the inputs in one string 
while(! input.equals("stop")) { 
    fruits += input + ","; // using comma to separate the inputs 
    input = scanner.nextLine(); 
} 
String[] res = fruits.split(","); // splitting the string to have its content in an array 
+0

嗨,非常感謝您使用代碼中的while部分。現在它爲我工作。 – Anu

+0

如果能幫助解決問題,請[接受答案](http://meta.stackexchange.com/a/5235/155831)。 –

相關問題