Search code examples
javaarraysjava-6

count words of sentences?


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

Solution

  • 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