2017-08-13 126 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