Aim:
To write a Java program that reads a string from the user and counts the frequency of
each character using a HashMap.
Algorithm:
1. Start the program and import required classes for HashMap and Scanner.
2. Read a string input from the user using the Scanner class.
3. Initialize an empty HashMap to store character-frequency pairs.
4. Convert the string into a character array using toCharArray().
5. Traverse each character of the array using a for-each loop.
6. For each character, update its frequency count in the HashMap.
7. Print the characters and their corresponding frequencies.
8. Close the Scanner object and end the program.
Source Code:
import [Link];
import [Link];
import [Link];
public class CharacterFrequency {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Input string
[Link]("Enter a string: ");
String input = [Link]();
// Count frequencies
Map<Character, Integer> frequencyMap = countCharacterFrequency(input);
// Display results
[Link]("\nCharacter frequencies:");
for ([Link]<Character, Integer> entry : [Link]()) {
[Link]("'" + [Link]() + "' : " + [Link]());
}
[Link]();
}
// Function to count character frequencies
public static Map<Character, Integer> countCharacterFrequency(String str) {
Map<Character, Integer> freqMap = new HashMap<>();
for (char ch : [Link]()) {
// If character already in map, increment count; else put 1
[Link](ch, [Link](ch, 0) + 1);
}
return freqMap;
}
}
Sample Output:
Enter a string: hello world
Character frequencies:
'h' : 1
'e' : 1
'l' : 3
'o' : 2
'':1
'w' : 1
'r' : 1
'd' : 1