Search code examples
javahistogramfrequency

How to make a frequency histogram in java


I am trying to create a code that reads through a file and prints out the following:

  • number of lines of the file
  • the frequency of each letter
  • the frequency of each non-alphabetic character

I want to create a histogram for the frequency of the letters and numbers but I can't seem to find a solution around it. If anything i would want the output to look like this:

A ***** - 5
B *** - 3
C ******* - 7

My output looks like this:

*********************
*********************
*********************
A 263
B 130
C 50

etc.


Solution

  • This is how you do the task. It counts the number of lower case letters and prints the stars as well in addition to the frequency, just as you wanted.

    Here is the general code (paragraph is the string that contains the content of your file):

    int[] lettercount = new int[26];
    for(int i = 0; i < 26; i++){
        //Set every single number in the array to 0.
        lettercount[i] = 0;
    }
    
    for(char s : paragraph.toCharArray()){
        int converted = (int) s;
        converted -= 97;
        if(converted >=0 && converted <=25){
            lettercount[converted] += 1;
        }
    }
    
    //Print out the letter with the frequencies.
    for(int i = 0; i < 26; i++){
        char convertback = (char) (i+97);
        String stars = "";
        for(int j = 0; j < lettercount[i]; j++){
            stars += "*";
        }
        System.out.println(convertback + " " + stars + " - " + lettercount[i]);
    }
    

    This should work for lowercase letters. If you want to do uppercase letters, lettercount[] should be 52 elements long. You would also have to check if converted (in the second for loop), after subtracting 97 is negative, and if it is, you would add back 58.

    I hope this helps! If you have any problems, just comment below.