Explanation
This Java program, named WordCount, is designed to read an entire line of text entered by the user and accurately count how many words are present in that input string.
The process begins by setting up a Scanner object to read input from the standard input stream (the console). It then prompts the user to "Enter a string:". The user's input, which might contain leading, trailing, or multiple spaces between words, is captured using sc.nextLine().
The core logic involves two crucial preprocessing steps:
- Trimming:
input.trim()is called first. This removes any whitespace characters (spaces, tabs) from the beginning and the end of the string. This ensures that leading or trailing spaces do not result in empty strings being counted as words later. - Handling Empty Input: A check is performed using
input.isEmpty(). If the string is empty after trimming (meaning the user only entered spaces or nothing at all), the program correctly reports "Number of words: 0".
If the string is not empty, the program proceeds to count the words using the split(" ") method. This method divides the input string into an array of substrings (words) wherever a single space character is encountered. Finally, the length of this resulting array (words.length) gives the total count of words, which is then printed to the console. The Scanner is properly closed at the end to release system resources.