-5

i want to count number of words per sentences i write code but count character for each word in sentences this my code

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
    Count the number of spaces " " + 1 –  Aug 13 '17 at 21:36
  • Welcome to Stack Overflow! Please review our [SO Question Checklist](http://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist) to help you to ask a good question, and thus get a good answer. – Joe C Aug 13 '17 at 21:36
  • https://stackoverflow.com/a/5864184/3010171 – Christian Moen Aug 13 '17 at 22:10

2 Answers2

1

String[] count_words= sentences.split(" "); is splitting the input argument by " " that means that length of this array is the number of words. simply print the length out.

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);
}

example:

oliverkoo@olivers-MacBook-Pro ~/Desktop/untitled folder $ java Main
Please type some words, then press enter: 
my name is oliver
number of word is 4
OLIVER.KOO
  • 5,654
  • 3
  • 30
  • 62
0

The method call count.length() is returning the length of each word because the loop is assigning each word to variable count. (This variable name is very confusing.)

If you want the number of words in the sentence, you need the size of the count_words array, which is count_words.length.

Kirby
  • 704
  • 4
  • 7