Introduction
Counting the occurrences of each character in a string is a common task in text processing. This exercise helps you understand how to manipulate strings and use data structures like maps in Java to store and count character occurrences. This guide will walk you through writing a Java program that counts the occurrences of each character in a given string.
Problem Statement
Create a Java program that:
- Prompts the user to enter a string.
- Counts the number of occurrences of each character in the string.
- Displays each character along with its count.
Example:
- Input: "programming"
- Output:
p: 1 r: 2 o: 1 g: 2 a: 1 m: 2 i: 1 n: 1
Solution Steps
- Read the String: Use the Scannerclass to take the string as input from the user.
- Initialize a Map: Use a HashMapto store each character of the string as keys and their counts as values.
- Iterate Through the String: Loop through each character in the string and update the count in the map.
- Display the Character Counts: Print each character along with its count.
Java Program
// Java Program to Count the Occurrences of Each Character in a String
// Author: https://www.rameshfadatare.com/
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class CharacterOccurrenceCounter {
    public static void main(String[] args) {
        // Step 1: Read the string from the user
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.print("Enter a string: ");
            String input = scanner.nextLine();
            
            // Step 2: Initialize the map to store character counts
            Map<Character, Integer> charCountMap = new HashMap<>();
            
            // Step 3: Iterate through the string
            for (char ch : input.toCharArray()) {
                charCountMap.put(ch, charCountMap.getOrDefault(ch, 0) + 1);
            }
            
            // Step 4: Display the character counts
            System.out.println("Character occurrences:");
            for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
                System.out.println(entry.getKey() + ": " + entry.getValue());
            }
        }
    }
}
Explanation
Step 1: Read the String
- The Scannerclass is used to read a string input from the user. ThenextLine()method captures the entire line as a string.
Step 2: Initialize the Map
- A HashMapis used to store each character as a key and its count as the value. This allows for efficient lookups and updates of character counts.
Step 3: Iterate Through the String
- A forloop is used to iterate over each character in the string, usingtoCharArray()to convert the string into a character array.
- The getOrDefault()method checks if the character is already in the map. If it is, the count is incremented by 1; if not, the character is added to the map with a count of 1.
Step 4: Display the Character Counts
- The program iterates through the HashMapentries and prints each character along with its count usingSystem.out.println().
Output Example
Example:
Enter a string: programming
Character occurrences:
p: 1
r: 2
o: 1
g: 2
a: 1
m: 2
i: 1
n: 1
Conclusion
This Java program demonstrates how to count and display the occurrences of each character in a user-input string. It covers essential concepts such as string manipulation, using maps to store character counts, and iterating through collections, making it a valuable exercise for beginners learning Java programming.