计算字母频率

时间:2018-02-20 17:51:33

标签: java arrays

以下代码来自我的旧讲义,我忘记了为什么我们需要         letters[index]++在这里?有人可以解释我们为什么需要它吗?

public class CountLetterFrequencies {

    /* Private instance variables */
    private static int[] letters = new int[26];

    public static void main(String[] args) {
        System.out.println("This program counts letter frequencies. Enter text:");

        Scanner sc = new Scanner(System.in);

        String line = sc.nextLine(); 

        countLetterFrequencies(line);

        printFrequencyTable();

        sc.close();
    }

    /* Counts the letter frequencies in a line of text */
    private static void countLetterFrequencies(String line) {
        for (int i = 0; i < line.length(); i++) {
            char ch = line.charAt(i);
            if (Character.isLetter(ch)) { // Character.isLetter(ch)
                int index = Character.toUpperCase(ch) - 'A'; // index = C - A = 2
                letters[index]++;
            }
        }
    }

private static void printFrequencyTable() {
        for (char ch = 'A'; ch <= 'Z'; ch++) {
            int index = ch - 'A'; // So, if ch is B, then index => B-A => 1
            if(letters[index] != 0) // if we wanna print only existing letters
                System.out.println(ch + ": " + letters[index]);
        }
    }

}

1 个答案:

答案 0 :(得分:2)

 int index = Character.toUpperCase(ch) - 'A'; 

index为您提供数组中存储该特定计数的位置。

letters[index]++;

然后它会增加该特定字符的数量。

明白这个

 index = Character.toUpperCase(ch) - 'A';

&#39; A&#39; - &#39; A&#39;这将给出数组位置0

&#39; B&#39; - &#39; A&#39;这将给出数组位置1,即B计数位置,依此类推 直到

&#39; Z&#39; - &#39; A&#39;这将给出数组的位置25,其中&#39; Z&#39;将被存储

它执行ASCII值减法

代表

 'A' - 'A' it will do 65-65 =0    65 is ascii value of 'A'

 'B' - 'A' it will do 66-65 =1

 'Z' - 'A' it will do 90-65 = 25