CountWords.java
import java.util.Scanner; /** * @author Candid Java */ public class CountWords { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter your text: "); String str = input.nextLine(); int count = str.trim().split("[\\s]+").length; System.out.println("Your text has " + count + " word(s)"); input.close(); } }
Output
Enter your text: WELCOME TO CANDID JAVA Your text has 4 word(s)