0

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.

4

1 に答える 1

0

1 - Java で int のストリームを char に変換する前に回答済み

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

2 - 最大カウントにタイプミスがあります:

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

frequencies.lengthniz.length() の代わりに使用します。

3 - 何を尋ねているのかわからない。入力文字列の一意の文字? frequencies[i] > 0最大ループで機能するかどうかを確認してください。

于 2013-11-10T17:44:07.610 に答える