Introduction
Counting the occurrences of each character in a string is a common task in text processing and analysis. This guide will show you how to create a Java program that counts and displays the frequency of each character in a given string.
Problem Statement
Create a Java program that:
- Takes a string as input.
- Counts and displays the frequency of each character in the string.
Example 1:
- Input:
"hello"
- Output:
h: 1, e: 1, l: 2, o: 1
Example 2:
- Input:
"programming"
- Output:
p: 1, r: 2, o: 1, g: 2, a: 1, m: 2, i: 1, n: 1
Solution Steps
- Prompt for Input: Use the
Scanner
class to read a string input from the user. - Use a
HashMap
to Track Character Frequencies: Iterate through the string and store the frequency of each character in aHashMap
. - Display the Character Frequencies: Print the frequency of each character in the string.
Java Program
Java Program to Count the Occurrences of Each Character
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/**
* Java Program to Count the Occurrences of Each Character in a String
* Author: https://www.javaguides.net/
*/
public class CharacterFrequencyCounter {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Step 1: Prompt the user for input
System.out.print("Enter a string: ");
String input = scanner.nextLine();
// Step 2: Use a HashMap to track character frequencies
Map<Character, Integer> charCountMap = new HashMap<>();
for (char c : input.toCharArray()) {
charCountMap.put(c, charCountMap.getOrDefault(c, 0) + 1);
}
// Step 3: Display the character frequencies
System.out.println("Character frequencies:");
for (Map.Entry<Character, Integer> entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
Explanation
- Input: The program prompts the user to enter a string.
- Tracking Character Frequencies: The program uses a
HashMap
to count the occurrences of each character in the string. ThegetOrDefault
method is used to increment the count if the character already exists in the map or to initialize it if it does not. - Displaying Frequencies: The program then iterates over the
HashMap
to display each character and its corresponding frequency.
Output Example
Example 1:
Enter a string: hello
Character frequencies:
h: 1
e: 1
l: 2
o: 1
Example 2:
Enter a string: programming
Character frequencies:
p: 1
r: 2
o: 1
g: 2
a: 1
m: 2
i: 1
n: 1
Example 3:
Enter a string: javaguides
Character frequencies:
j: 1
a: 2
v: 1
g: 1
u: 1
i: 1
d: 1
e: 1
s: 1
Conclusion
This Java program effectively counts the occurrences of each character in a string using a HashMap
. By tracking the frequency of each character, the program can display the exact number of times each character appears in the input string. This approach is practical for various text processing tasks, such as analyzing text or ensuring data integrity.
Comments
Post a Comment
Leave Comment