2017-08-13 1 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 –

+0

ようこそスペースの数を数えます!良い質問をするのを助けるために私たちの[SO Question Checklist](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である必要があります。