gpt4 book ai didi

java - 需要 : array or java. lang.Iterable

转载 作者:行者123 更新时间:2023-11-29 10:01:47 26 4
gpt4 key购买 nike

我是 Java 的初学者。我只想计算文本文件中每个单词的出现次数。输入格式就像:

A B
A C
C A
B C

这是我到目前为止所做的:

public static void main (String[] args) throws FileNotFoundException
{
Scanner inputFile = new Scanner(new File("test.txt"));
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
System.out.println(line);
// above is the first part, to read the file in
// below is the second part, try to count
Map<String, Integer> counts = new HashMap<>();
for (String word : line) {
Integer count = counts.get(word);
counts.put(word, count == null ? 1 : count + 1);
}
System.out.println(counts);
}
}

预期结果如下:

A 3
B 2
C 3

我在谷歌上找到了第一部分和第二部分,但不知道如何将它们结合起来。任何建议都会有所帮助。

最佳答案

您不能使用 for-each 循环遍历 String(变量 line)。您需要先将其拆分为如下单词:

   String[] words = line.split(" ");
for(String word : words) {
// do something
}

代码中似乎也有错误。用于管理计数的 Map 需要出现在 while 循环之外,否则计数将是特定行的本地计数。更改代码如下:

public static void main (String[] args) throws FileNotFoundException
{
Scanner inputFile = new Scanner(new File("test.txt"));
Map<String, Integer> counts = new HashMap<>();
while (inputFile.hasNextLine()) {
String line = inputFile.nextLine();
System.out.println(line);
// above is the first part, to read the file in
// below is the second part, try to count

String[] words = line.split(" ");
for (String word : words) {
Integer count = counts.get(word);
counts.put(word, count == null ? 1 : count + 1);
}

} // end of while

System.out.println(counts);
}

关于java - 需要 : array or java. lang.Iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23654884/

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