Java – Count the number of words in a Sentence

Hello people, this is a simple Java program to find out the number of words in a sentence. Very useful for high school / college students who are willing to learn Java Programming.

Here is the script:

import java.util.Scanner;

public class WordCount {

    public static void main(String[] args) {

        String sentence, trimmed;
        String[] words;
        int len;

        Scanner in = new Scanner(System.in);
        System.out.println("Enter a sentence:");
        sentence = in.nextLine();

        //remove the extra space between words
        trimmed = sentence.trim();

        //check if the entered string is null / empty
        if (trimmed.isEmpty()) {
            //if null print zero
            System.out.println(0);
        } else {

            //let's count the number of words by spliting it
            words = trimmed.split("\\s+");

            //find the length of the words
            len = words.length;

            System.out.println("Number of words: " +len);
        }

    }

}

Read the comments in the above program to understand what’s happening!!.

And the output of the program will be:

Enter a sentence:
spider man
Number of words: 2

Enjoy the day!

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top