Count Words
Count the number of words in a sentence.
BeginnerTopic: Module 4: String Programs
Java Count Words Program
This program helps you to learn the fundamental structure and syntax of Java programming.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a sentence: ");
String s = sc.nextLine().trim();
if (s.isEmpty()) {
System.out.println("Words: 0");
} else {
String[] words = s.split("\\s+");
System.out.println("Words: " + words.length);
}
sc.close();
}
}Output
Enter a sentence: hello world from java Words: 4
Understanding Count Words
We trim and split on one-or-more spaces, then take the array length.
Note: To write and run Java programs, you need to set up the local environment on your computer. Refer to the complete article Setting up Java Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your Java programs.