我正在尝试读取文件的内容并计算每个字母出现的频率。这是我的情况:
public static void readFile() throws Exception {
Map<Character, Integer> lcount = new HashMap<>();
for (Character letter = 'A'; letter <= 'Z'; letter++) {
lcount.put(letter, 0);
}
try {
FileReader reader = new FileReader("file.txt");
for (int i = 1; i != -1; i = reader.read()) {
int k = lcount.get((char) i);
lcount.put((char) i) ,k++);
}
} catch (FileNotFoundException e) {
System.out.println("The file does not exist.");
}
}
我不能使用(char(i,k ++(来增加HashMap中的字母计数。
异常说:将(字符,整数(在映射中不能应用于(字符(
如何在位置 i 读取 Character 类型的值,并将其用作键以在我的 HashMap 中为其输入值?
提前谢谢。
编辑:感谢@Ferrybig。我只是错过了一个"("。我以为是关于 变量类型。
使用k + 1
:
for (int i = 1; i != -1; i = reader.read()) {
int k = lcount.get((char) i);
lcount.put((char) i, k + 1);
}
k++
返回k
的原始值(在增量之前(。
或:
for (int i = 1; i != -1; i = reader.read()) {
lcount.put((char) i, lcount.get((char) i) + 1);
}
没有方法 get((:
for (int i = 1; i != -1; i = reader.read()) {
lcount.compute((char) i, (x, i) -> i + 1);
}