Search code examples
javaasciifrequencysign

Sign frequency, highest frequency, number of signs


Java. Converting a string into its ASCII code equivalent and:

public class Loop {
    public static void main (String[] args) {
        BralecPodatkov bp = new BralecPodatkov();     // allows me to write string
        System.out.println("Type string: ");
        String niz = bp.beriNiz();                    // reads my string
        int[] frequencies = new int [128];     // all 128 ASCII signs
        int total = 0;

        System.out.println("N of signs: " + niz.length());     // sum of all signs

        for (int i = 0; i < niz.length(); i++) {
            int ascii = (int) niz.charAt(i);
                frequencies[ascii]++;
                total += 1;
        }

        for (int i = 0; i < frequencies.length; i++) {
            if (frequencies[i] > 0)
                System.out.print(" " + (((float) frequencies[i]/total)*100) + "%");
          else
                System.out.print(" 0%");     // prints all sign frequencies in %
        }               

        int max = frequencies[0];
        for (int i = 0; i < niz.length(); i++) {
            if (frequencies[i] > max) {
                max = frequencies[i];     // print sign with highest frequency
            }
        }
    System.out.println("\n" + "Max number: " + max);     
    }
}

Result:

Type string: 
1234               // arbitrary string that I insert
N of signs: 4
 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 25.0% 25.0% 25.0% 25.0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0% 0%
Max number: 0

Code to read a string and print out: the sum of all signs, the frequency of every sign (in %) and the sign with the highest frequency. Questions:
1) How can I add the appropriate sign before each frequency? (e.g. 1 = 25%, 2 = 25%, ...)
2) My max number frequency code is not working, it always prints out 0. What am I doing wrong?
3) How to count the number of unique signs of the string?

Also if you find any mistakes, complications or have any comments do let me know.


Solution

  • 1 - Has been answered before Converting stream of int's to char's in java

    for (int i = 0; i < frequencies.length; i++) {
            System.out.print( Character.toChars(i) );
            System.out.print( " = ");
            if (frequencies[i] > 0)
    

    2 - The max counting has a typo:

        int max = frequencies[0];
        for (int i = 0; i < niz.length(); i++) {
    

    Use frequencies.length instead of niz.length().

    3 - Not sure what you are asking. The unique characters in the input string? Just see if frequencies[i] > 0 in the max loop would work.