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/

相关文章:

java - 在 spring xml 配置中连接字符串

java - 当OutputStream的write写入字节(内部)时,为什么InputStream的read返回int?

javascript - 每隔几秒从数组中的值更改类

python - 如何将视频转换为 numpy 数组?

C++ 字符串数组搜索每个项目的输出

java - 在以编程方式配置 Jetty 嵌入式服务器中使用 HttpRequestHandler Servlet

java - 使用 String IV 进行 AES 加密

java - Gatling Maven 插件和 Maven 3.3.3

java - 在Java中通过txt文件创建对象到数组中

javascript - 使用 foreach 或带有 javascript 的 map 将复杂对象添加到数组中