2017-08-13 112 views
-5

我要計算每個句子我寫碼字的數量,但在句子數字每個字這是我的代碼計數句子的單詞?

public static void main(String [] args){ 
    Scanner sca = new Scanner(System.in); 
    System.out.println("Please type some words, then press enter: "); 
    String sentences= sca.nextLine(); 
    String []count_words= sentences.split(" "); 
    for(String count : count_words){ 
    System.out.println("number of word is "+count.length());} 
} 
+1

計數的空格數 「」 + 1 – 2017-08-13 21:36:36

+0

歡迎堆棧溢出!請查看我們的[SO問題清單](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist)來幫助你提出一個好問題,從而得到一個很好的答案。 –

+0

https://stackoverflow.com/a/5864184/3010171 –

回答

1

String[] count_words= sentences.split(" ");正在拆分輸入參數" "這意味着此數組的長度是單詞的數量。只需打印出長度。

public static void main(String[] args) { 
    Scanner sca = new Scanner(System.in); 
    System.out.println("Please type some words, then press enter: "); 
    String sentences= sca.nextLine(); 
    String[] count_words= sentences.split(" "); 
    System.out.println("number of word is "+ count_words.length); 
} 

例如:

[email protected] ~/Desktop/untitled folder $ java Main 
Please type some words, then press enter: 
my name is oliver 
number of word is 4 
0

方法調用,因爲循環分配每個字count.length()將返回每個單詞的長度到變量count。 (這個變量的名字很混亂。)

如果你想要句子中單詞的數量,你需要count_words數組的大小,即count_words.length