Java Program to Count Words in a Given Text
This program counts the number of words in a given text. It uses Java’s built-in string manipulation methods to achieve this. Below is the complete Java program along with a detailed explanation of its structure and functionality.
Program Structure and Explanation
The program consists of a single class WordCounter
with the following components:
main
method: This is the entry point of the program. It calls thecountWords
method with a sample text.countWords
method: This method takes a string as input and returns the number of words in it. It uses thesplit
method of theString
class to split the text into words based on spaces and returns the length of the resulting array.
Java Code
/**
* WordCounter.java
*
* This program counts the number of words in a given text.
*/
public class WordCounter {
/**
* The main method is the entry point of the program.
* @param args Command line arguments
*/
public static void main(String[] args) {
String text = "This is a sample text to count the number of words.";
int wordCount = countWords(text);
System.out.println("The number of words in the given text is: " + wordCount);
}
/**
* This method counts the number of words in the given text.
* @param text The input text
* @return The number of words in the text
*/
public static int countWords(String text) {
// Split the text by spaces to get individual words
String[] words = text.split("\\s+");
// Return the number of words
return words.length;
}
}
Explanation of Key Components
main Method
The main
method is where the program starts execution. It contains a sample text and calls the countWords
method to count the number of words in this text. The result is then printed to the console.
countWords Method
The countWords
method is a static method that takes a string as input. It uses the split
method of the String
class with a regular expression "\\s+"
to split the text into words. The regular expression "\\s+"
matches one or more whitespace characters. The method then returns the length of the resulting array, which represents the number of words in the input text.
Sample Output
When the program is executed with the sample text “This is a sample text to count the number of words.”, the output will be:
The number of words in the given text is: 10