A Word Counter is a classic and practical mini-project that’s perfect for those new to Java. It’s easy to build but teaches important lessons about user input, string manipulation, loops, and collections. Let’s break down the project step by step with beginner-friendly explanations and code.
What Will This Word Counter Do?
- Accept a line of text from the user (a sentence or paragraph).
- Count the total number of words.
- (Optionally) Count the occurrences of each word (word frequency).
- Display the results to the user.
This project is console-based, simple, and can be expanded as you gain confidence.
Step 1: Java Concepts Practiced
- Reading user input (
Scanner) - Using and manipulating
Stringobjects - Splitting strings into words using
.split() - Using loops to traverse arrays
- (Optionally) Counting word occurrences with
HashMap
Step 2: Import Required Classes
java
import java.util.Scanner;
import java.util.HashMap; // Needed for word frequencies
Step 3: Read a Line from the User
We’ll ask the user to enter some text. We’ll read the entire line so we can handle sentences and spaces.
java
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence or paragraph: ");
String text = scanner.nextLine();
Step 4: Split the Text Into Words
We use the .split() method to break our text into an array of individual words.
java
// Split by whitespace using regex "\\s+"
String[] words = text.trim().split("\\s+");
-
trim()removes extra spaces at the beginning/end. -
"\\s+"is a regex that matches one or more whitespace characters (spaces, tabs).
Step 5: Count the Words
The total number of words is simply the length of our words array.
java
int wordCount = words.length;
System.out.println("Total words: " + wordCount);
Step 6: (Optional) Count Each Word’s Frequency
To make the program more useful, you can count how many times each word appears using a HashMap.
java
HashMap<String, Integer> wordFreq = new HashMap<>();
for (String w : words) {
w = w.toLowerCase(); // Ignore case for counting
if (wordFreq.containsKey(w)) {
wordFreq.put(w, wordFreq.get(w) + 1);
} else {
wordFreq.put(w, 1);
}
}
// Print the results
System.out.println("Word frequencies:");
for (String w : wordFreq.keySet()) {
System.out.println(w + ": " + wordFreq.get(w));
}
Step 7: Complete Code for Word Counter
Here’s the full, beginner-friendly version that counts both total words and their frequencies:
java
import java.util.Scanner;
import java.util.HashMap;
public class WordCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a sentence or paragraph: ");
String text = scanner.nextLine();
// Remove leading/trailing spaces and split into words
String[] words = text.trim().split("\\s+");
int wordCount = words.length;
System.out.println("Total words: " + wordCount);
// Count word occurrences (case-insensitive)
HashMap<String, Integer> wordFreq = new HashMap<>();
for (String w : words) {
w = w.toLowerCase();
if (wordFreq.containsKey(w)) {
wordFreq.put(w, wordFreq.get(w) + 1);
} else {
wordFreq.put(w, 1);
}
}
System.out.println("Word frequencies:");
for (String w : wordFreq.keySet()) {
System.out.println(w + ": " + wordFreq.get(w));
}
scanner.close();
}
}
Step 8: How to Run the Project
1.Copy the code into a file named WordCounter.java.
2.Open a terminal in the file’s directory.
3.Compile the code:
text
javac WordCounter.java
4.Run the program:
text
java WordCounter
Enter any sentence or paragraph. See the word count and frequency for each word!
Key Concepts Practiced
-
User Input: Using
Scannerfor flexible string input. -
String Manipulation: Using
trim(),split(), and converting to lowercase. -
Loops & Collections: Processing arrays and using
HashMapto store word counts. - Basic Output: Nicely displaying the total and per-word statistics.
Project Ideas for Expansion
- Ignore punctuation (remove
,.;!?etc. before splitting words). - Sort the frequency output alphabetically or by frequency.
- Support multi-line paragraphs (until the user enters a special word, e.g., “END” to finish).
- Allow the user to search for the frequency of a specific word.
Why This Project is Perfect for Beginners
- Small and manageable codebase.
- Immediate, visible results build confidence.
- Teaches fundamental Java programming skills.
- Easily extendable with more features as you learn.
Building a Word Counter gives you hands-on practice with everyday Java tools. Tweak the code, experiment, and expand your skills as you go – and watch your Java knowledge grow sentence by sentence!
Check out the YouTube Playlist for great java developer content for basic to advanced topics.
Please Do Subscribe Our YouTube Channel for clearing programming concept and much more ... : CodenCloud
Top comments (0)