Count Words in Java
Count the number of words in a sentence.
BeginnerModule 4: String ProgramsExample 5 of 25
count-words.java
1import java.util.Scanner;23public class Main {4 public static void main(String[] args) {5 Scanner sc = new Scanner(System.in);6 System.out.print("Enter a sentence: ");7 String s = sc.nextLine().trim();89 if (s.isEmpty()) {10 System.out.println("Words: 0");11 } else {12 String[] words = s.split("\\s+");13 System.out.println("Words: " + words.length);14 }15 sc.close();16 }17}
Output
Enter a sentence: hello world from java Words: 4
What's going on
We trim and split on one-or-more spaces, then take the array length.