How to print histogram of frequencies of characters in string with Java

1 Answer

0 votes
public class MyClass {
    public static void main(String args[]) {
        int[] lettercount = new int[256];
        String s = "Java is a high-level, class-based, object-oriented programming language";
    
        for (char ch : s.toCharArray()) {
            lettercount[(int)ch] += 1;
        }

        for (int i = 0; i < 256; i++) {
            if (lettercount[i] != 0) {
                String stars = "";
                for(int j = 0; j < lettercount[i]; j++){
                    stars += "*";
                }
                System.out.println((char)i + " " + stars );
            }
        }
    }
}



/*
run:

  *******
, **
- ***
J *
a ********
b **
c **
d **
e *******
g *****
h **
i ****
j *
l ****
m **
n ***
o ***
p *
r ***
s ****
t **
u *
v **

*/

 



answered Oct 3, 2021 by avibootz
...