下面的代码来 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/