gpt4 book ai didi

java - 文本文件中字母的频率。输出小问题

转载 作者:行者123 更新时间:2023-12-02 03:04:16 25 4
gpt4 key购买 nike

所以这个方法应该读取一个文本文件并输出每个字母的频率。文本文件内容如下:

  • aaaa
  • bbb
  • 抄送

所以我的输出应该是:

  • a = 4
  • b = 3
  • c = 2

不幸的是,我的输出是:

  • a = 4
  • a = 4
  • b = 3
  • a = 4
  • b = 3
  • c = 2

有谁知道为什么吗?

我尝试修改循环,但仍然没有解决这个问题。

public void getFreq() throws FileNotFoundException, IOException, Exception {

File file = new File("/Users/guestaccount/IdeaProjects/Project3/src/sample/testFile.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<Character, Integer> hash = new HashMap<>();
String line;

while ((line= br.readLine()) != null) {
line = line.toLowerCase();
line = line.replaceAll("\\s", "");

char[] chars = line.toCharArray();
for (char c : chars) {
if (hash.containsKey(c)){
hash.put(c, hash.get(c)+1);
}else{
hash.put(c,1);
}
}
for (Map.Entry entry : hash.entrySet()){
System.out.println(entry.getKey() + " = " + entry.getValue());
}


}
}

最佳答案

Chrisvin Jem 为您提供了要更改的代码,因为您的 for循环在你的 while 中从 File 读取时循环.

Does anyone know why?

正如您的问题所述,我将解释为什么它会给您这样的输出。

原因:它为您提供输出 a=4, a=4, b=3, a=4, b=3, c=3 的原因是因为你的for循环在你的 while 中循环意味着每次BufferedReader读取新行,您迭代了 HashMap并打印其内容。

示例:BufferedReader读取文件的第二行 HashMap hash已经有 a 的键值对现在,它刚刚获得 b 的值。结果,除了已经打印了 a 的值之外,当读取第一行时,它还会打印 HashMap 的当前内容,包括冗余的a 。文件的第三行也会发生同样的情况。

解决方案:通过移动 for循环出while循环,您只打印 HashMap 之后的结果具有其所有值,并且 HashMap仍在获取值。

for (Map.Entry entry : hash.entrySet())
System.out.println(entry.getKey() + " = " + entry.getValue());

我希望这个答案能够解释为什么您会得到该特定输出

关于java - 文本文件中字母的频率。输出小问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57031234/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com