0

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

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);
}
}
4

4 回答 4

1

试试这个,而不是只打印总和:

for(String day : theKeywords) {
 System.out.println(day + " = " + DayCount.get(day));
}
于 2013-03-05T19:25:22.950 回答
1

您正在打印所有天数的总和。相反,您想打印每天的值。所以而不是

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

你应该做

for(String Day: theKeywords) {
 System.out.println(Day+ " = " + DayCount.get(day));
}
于 2013-03-05T19:28:15.050 回答
0

试试这个:

for (String crtDay : dayCount.keySet())
    System.out.println(String.format("%s = %d", crtDay, dayCount.get(crtDay));
于 2013-03-05T19:24:16.287 回答
0

只需这样做:

for (Entry<String, Integer> count: DayCount.entrySet())
    System.out.println(count.getKey()+" = "+count.getValue());
于 2013-03-05T19:25:24.230 回答