0

我有一个程序可以对字母在故事中出现的次数进行排序和计数。我遇到的一个问题是我需要打印这封信以及它在排序时出现的次数。

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"
    }

有没有办法让我得到排序后的字母和它们的值?

4

1 回答 1

0

您是否考虑过使用 aMap<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);
    }
}

然后,您有一张按字母排序的字符数对的地图。然后,您可以使用此树来查找最大值和最小值。

于 2013-04-10T18:43:32.027 回答