Java Online Compiler
Example: Character Frequency Counter in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Character Frequency Counter import java.util.Scanner; // Main class containing the entry point of the program public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Step 1: Prompt user for input string System.out.print("Enter a string: "); String inputString = scanner.nextLine(); // Step 2: Define the size of the frequency array // We assume extended ASCII characters (0-255). // For full Unicode, a HashMap would be more appropriate. int[] frequency = new int[256]; // Array to store character counts // Step 3: Iterate through the string using a for loop // For each character, increment its count in the frequency array. for (int i = 0; i < inputString.length(); i++) { char ch = inputString.charAt(i); // Convert character to its ASCII value and use as index frequency[ch]++; } // Step 4: Iterate through the frequency array to print results System.out.println("Character frequencies:"); for (int i = 0; i < frequency.length; i++) { // Check if the character appeared at least once if (frequency[i] > 0) { // Convert the ASCII index back to a character System.out.println((char) i + ": " + frequency[i]); } } scanner.close(); } }
Output
Clear
ADVERTISEMENTS