爪哇。将字符串转换为其等效的 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)如何计算字符串的唯一符号数?
此外,如果您发现任何错误、并发症或有任何意见,请告诉我。