Explanation
This Java program is designed to read a line of text (a string) from the user and then accurately count the number of words present in that string. It handles common issues like leading/trailing spaces and empty inputs.
Here's a step-by-step breakdown of its logic:
- Import Scanner: The program begins by importing the
java.util.Scannerclass, which is essential for reading user input from the console. - Create Scanner Object: Inside the
mainmethod, an object of theScannerclass is created, linked toSystem.in(the standard input stream), allowing the program to receive input. - Prompt User: The program then displays a message "Enter a string: " to guide the user to input text.
- Read Input: It reads the entire line of text entered by the user, including spaces, until the user presses Enter, and stores it in a
Stringvariable namedinput. - Trim Spaces: Crucially, the
input.trim()method is called. This method removes any leading (beginning) and trailing (ending) whitespace characters (spaces, tabs, newlines) from theinputstring. This is important because leading/trailing spaces should not be counted as part of a word or affect the word count. - Handle Empty String: After trimming, the program checks if the
inputstring is empty usinginput.isEmpty(). If the string is empty (meaning the user entered nothing, or only spaces which were then trimmed), it directly prints "Number of words: 0". This is an important edge case handling. - Split into Words: If the string is not empty, the core logic for counting words is executed.
input.split(" ")is called. This method breaks the string into an array of substrings wherever a space (" ") is encountered. Each resulting substring is considered a word. For example, "Hello World" would become an array{"Hello", "World"}. - Count and Display: The
words.lengthproperty gives the total number of elements in thewordsarray, which directly corresponds to the number of words found. This count is then printed to the console. - Close Scanner: Finally,
sc.close()is called to release the resources associated with theScannerobject, which is good practice.