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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
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!