gpt4 book ai didi

java - Java 中统计文本文件中字符串的出现次数

转载 作者:行者123 更新时间:2023-12-02 07:13:32 29 4
gpt4 key购买 nike

我正在尝试计算文本文件中一周中出现的天数。截至目前,我的代码计算出现的总数,但我需要它来计算每个关键字单独出现的次数。输出需要如下所示

Monday = 1
Tuesday = 2
Wednesday = 0

等等

这是我到目前为止的代码

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import java.util.HashMap;

public class DayCounter
{

public static void main(String args[]) throws IOException
{

String[] theKeywords = { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

// put each keyword in the map with value 0
Map<String, Integer> DayCount = new HashMap<String, Integer>();
for (String str : theKeywords)
{
DayCount.put(str, 0);
}

try (BufferedReader br = new BufferedReader(new FileReader("C:\\Eclipse\\test.txt")))
{

String sCurrentLine;

// read lines until reaching the end of the file
while ((sCurrentLine = br.readLine()) != null)
{


if (sCurrentLine.length() != 0)
{

// extract the words from the current line in the file
if (DayCount.containsKey(sCurrentLine))
{
DayCount.put(sCurrentLine, DayCount.get(sCurrentLine) + 1);
}
}
}

}
catch (FileNotFoundException exception)
{

exception.printStackTrace();
}
catch (IOException exception)
{

exception.printStackTrace();
}


int count = 0;
for (Integer i : DayCount.values())
{
count += i;
}

System.out.println("\n\nCount = " + count);
}
}

最佳答案

尝试这个而不是仅仅打印总和:

for(String day : theKeywords) {
System.out.println(day + " = " + DayCount.get(day));
}

关于java - Java 中统计文本文件中字符串的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15232268/

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