Count Words

Count the number of words in a sentence.

JavaBeginner
Java
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

We trim and split on one-or-more spaces, then take the array length.