java - 计算字母频率

标签 java arrays

下面的代码来 self 以前的讲义,我忘记了为什么我们需要 字母[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]);
        }
    }

}

最佳答案

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

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

letters[index]++;

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

明白这个

 index = Character.toUpperCase(ch) - 'A';
  • 'A' - 'A' 这将给出数组位置 0
  • 'B' - 'A' 这将给出数组位置 1,即 B 计数位置,依此类推,直到
  • 'Z' - 'A' 这将给出数组的位置 25,其中将存储 'Z' 的计数

它进行 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

关于java - 计算字母频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48891376/

相关文章:

javascript - 如何根据另一个对象数组对一个对象数组进行排序

c - 大小为 LONG_MAX 的数组

java - 如何在java库中处理异步响应?

java - 我可以将 php 和 java 用于同一个 Web 应用程序吗

python - 从python中的二维数组中随机采样子数组

JavaScript - 用数组助手替换 for 循环

ios - 将内容添加到 NSUserDefaults - 多个 View

java - 释放所有等待线程

java - 为什么我必须重复输入才能让我继续?

java - 如何以 Logbacks 的 HTML 格式输出亚洲字符