我有一个程序可以对一个字母出现在故事中的出现次数进行排序和计算。我遇到的一个问题是我需要打印字母及其排序时的次数。
if (line == null) break; //check for end of file before doing anything
line=line.toLowerCase();
for (int i = 0 ; i < line.length(); i++ ) {
letter = line.charAt(i);
int num = (int)letter;
num-=96;
if(num>=1 && num<=26) alpha[num]++;
}
for(int j=1; j<=26; j++) System.out.println((char)(j+64) +" = "+alpha[j]);
int[] minArr = new int[6];
int[] maxArr = new int[6];
Arrays.sort(alpha);
// System.out.print("There are "+max+" and "+min);
for(int n=1;n<=5;n++) {
System.out.println("is the highest with "+alpha[alpha.length-n]);
System.out.println("is the lowest with "+alpha[n]);
// int max = alpha.length-n;
// System.out.println((char)(min+64)+" has the least number of letters"
}
有没有办法能够获得带有值的排序字母?
答案 0 :(得分:0)
您是否考虑使用Map<String,Integer>
存储字数对?
有些事情:
SortedMap <String, Integer> alphaMap = new TreeMap<String, Integer>() {};
for (int i = 0 ; i < line.length(); i++ ) {
String letter = String.valueOf(line.charAt(i));
if (alphaMap.containsKey(letter)){
alphaMap.get(letter)++;
} else {
alphaMap.put(letter, 0);
}
}
然后,您有一个按字母排序的char计数对的映射。然后,您可以使用此树来查找最大值和最小值。