Answer to Question #160697 in Java | JSP | JSF for candice

Question #160697

Array Write a Java program to find frequency of each character in a given string. Also display the length and the most frequent among the characters


1
Expert's answer
2021-02-05T10:28:56-0500
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) {
        System.out.println("Input string:");
        Scanner scanner = new Scanner(System.in);
        String inputString = scanner. nextLine();
        
        int[] freq = new int[255];
        for (int i = 0; i < 255; i++)
            freq[i] = 0;
        
        for (int i = 0; i < inputString.length(); i++)
            freq[inputString.charAt(i)]++;
            
        for (int i = 0; i < 255; i++)
            if (freq[i] > 0)
                System.out.println((char) i + " : " + String.valueOf(freq[i]));
                
        System.out.println("The length "+String.valueOf(inputString.length()));
        
        int mostFrequent = 0;
        int frequency = 0;
        for (int i = 0; i < 255; i++)
            if (freq[i]>frequency)
            {
                mostFrequent = i;
                frequency = freq[i];
            }
            
        System.out.println("Most frequent is "+(char) mostFrequent+" with frequency "+String.valueOf(frequency));
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog