标志频率,最高频率,标志数量

时间:2013-11-10 17:19:49

标签: java ascii frequency sign

Java的。将字符串转换为等效的ASCII代码并且:

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);     
    }
}

结果:

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

读取字符串并打印输出的代码:所有符号的总和,每个符号的频率(以%为单位)和频率最高的符号。 问题:
1)如何在每个频率之前添加适当的符号? (例如1 = 25%,2 = 25%,......)
2)我的最大号码频率代码不起作用,它总是打印出来0.我做错了什么? 3)如何计算字符串的唯一符号数?

如果您发现任何错误,并发症或有任何意见,请告诉我。

1 个答案:

答案 0 :(得分:0)

1 - 在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 - 最大计数有错字:

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

使用frequencies.length代替niz.length()。

3 - 不确定你在问什么。输入字符串中的唯一字符?只需查看max循环中的frequencies[i] > 0是否有效。