简体   繁体   中英

Getting letters from an array

I have a program that sorts and counts the number of occurences that a letter appears in a story. The one issue I have is that I need to print the letter and the number of times it occurs while sorted.

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

Is there a way I am able to get the sorted letters with their values?

Have you considered using a Map<String,Integer> to store you char-count pairs?

Something along the lines of:

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

You then have a map of your char-count pairs that is ordered by letter. You can then use this tree to find you max and min values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM