【发布时间】:2022-01-24 18:42:31
【问题描述】:
我正在编写一个从文件中读取的代码,然后打印每个字母的频率
这是我的代码
BufferedReader read = new BufferedReader(new FileReader("Text.txt"));
BufferedWriter write = new BufferedWriter(new FileWriter("Output.text"));
String str = "";
str = read.readLine();
str = str.toUpperCase();
while ((str = read.readLine()) != null) {
int[] count = new int[26];
str = str.toUpperCase();
for (int i = 0 ; i < str.length(); i++) {
if (str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
count[str.charAt(i) - 'A']++;
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] >= 0) {
write.write("The frequency of letter " + (char) ('a' + i) + " = " + count[i]);
write.newLine();
}
}
}
但问题是代码会打印两次字母,即使我将字母转换为大写。 我该如何解决这个问题?
非常感谢你们
【问题讨论】:
-
你能显示你的输出文件吗?您是否尝试过在代码中设置断点?此外,您需要关闭输出编写器。
-
首先定位 where 打印两次。减少该打印语句,直到它仅打印错误的内容。涉及哪些变量?然后追溯:哪些代码行处理这些变量?他们在做什么?另外,请注意,您读取的第一个字符串被丢弃:您声明
str,将一行文本读入其中,将其设为大写,然后由于while ((str = read.readLine()) != null)而立即覆盖它。