2015-02-05 41 views
1

我想爲用戶輸入任何可能通過緩衝閱讀器輸入的單詞並將它們放入數組中。然後我想在單獨一行中打印每個單詞。所以我知道我需要某種字數計數器來計算用戶輸入的字數。這是我迄今爲止所做的。Java將一個字符串中的單詞打印到一個數組中

import java.text.*; 
import java.io.*; 

public class test { 
    public static void main (String [] args) throws IOException { 

     BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 
     String inputValue; 

     inputValue = input.readLine(); 
     String[] words = inputValue.split("\\s+"); 

可以說用戶輸入文字here is a test run。該程序應計數5個值,並打印出這樣的話

here 
is 
a 
test 
run 

任何幫助或建議,以何種方式來解決這個問題?

+2

你非常接近。提示:你正在尋找的是一個循環,可能是'for':[for循環](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html) –

回答

2

真的沒有必要計算單詞(除非你真的想)。你也可以使用一個for-each loop

String[] words = inputValue.split("\\s+"); 
for (String word : words) { 
    System.out.println(word); 
} 

正如我所說,如果你真的想,那麼你可以得到一個數組的length(你的「計數」),然後使用普通for圈像

String[] words = inputValue.split("\\s+"); 
for (int i = 0; i < words.length; i++) { 
    System.out.println(words[i]); 
} 

如果您不需要在單獨的行每個單詞,那麼你也可以使用Arrays.toString(Object[])和類似

String[] words = inputValue.split("\\s+"); 
System.out.println(Arrays.toString(words)); 
0

我希望我不回答作業。如果是這樣,你應該這樣標記它。您可以嘗試以下兩種方法。

BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); 
    String inputValue = input.readLine(); 
    String[] words = inputValue.split("\\s+"); 

    // solution 2 
    for(int i=0; i<words.length; i++){ 
     System.out.println(words[i]); 
    } 

    // solution 1 
    System.out.println(inputValue.replaceAll("\\s+", "\n")); 

現場演示:http://ideone.com/bCucIh

+0

不,這不是家庭作業大聲笑。 –

相關問題