我有计算文本文件中一周中出现的天数的代码。截至目前,如果它是该行上唯一的字符串,它只会计算星期几。例如,如果我有一条写着 (Monday abcd) 的行,它将不计入该星期一。我尝试使用 indexOf 并通过拆分、修剪和添加回哈希映射来解决此问题,但我不知道该怎么做。
下面是一些代码,在此之前我声明了关键字,打开文本文件并将每个关键字放入映射中,值为 0
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);
}
}
}
这是输出部分
for(String day : theKeywords)
{
System.out.println(day + " = " + DayCount.get(day));
}