curious4cs
curious4cs

Reputation: 193

counting number of occurrences per minute in java

I am trying to get the number of occurrences of data I am getting per minute. The date looks something like this. The first number is an integer representing the # of seconds since the Unix epoch which I convert into ISO 8601 time. The second is a double. The time ending in "00" represents the 0th minute and the one ending in "60" represents the 1st minute.

962668800 60.5
962668801 61.5
962668860 71.5

Code:

 public static void main(String args[] ) throws Exception {
            Scanner s = new Scanner(System.in);
            int count = 0;
            System.out.print("New minute found: ");

            while (s.hasNextLine()){
                int request = s.nextInt();
                double response = s.nextDouble();

                DateTimeFormatter d = secToDate(request); 
                int i = ldt.getSecond();

                if (i == 0){
                    System.out.print(count + " " + ldt.format(d) + "\n");
                    System.out.print("New Minute found: ");
                }else{
                    count++;
                }


            }
        } 

My output is this:

New minute found: 0 2000-07-04T00:00:00Z
New Minute found: 1 2000-07-04T00:01:00Z
New Minute found: 

but I'm looking for something like below (ignoring the new minute found text)

2000-07-04T00:00:00Z 2
2000-07-04T00:01:00Z 1

How do I tweak it such that I'm keeping track of the current minute and adding to the counter without printing out the counter prematurely?

Upvotes: 2

Views: 1237

Answers (1)

Eric Lippert
Eric Lippert

Reputation: 660169

How do I tweak it such that I'm keeping track of the current minute and adding to the counter without printing out the counter prematurely?

You don't tweak it. You start over with a better design. Your method is only 13 lines long and already it is doing too much. Your problem is that you have conflated computation and display.

Since it hurts when you do that, stop doing that. You're only 13 lines in; now would be a great time to start over.

Write a method that has this signature:

private static Dictionary<String, Integer> getMinuteCounts() { ... }

That method does one thing and one thing only. It computes a dictionary which maps strings representing the minute onto the count of observed minutes. It does absolutely nothing else.

Now write a method that has this signature:

private static void displayMinuteCounts(Dictionary<String, Integer> d) { ... }

That thing does one thing and one thing only: it displays the counts computed.

Now your main method body is:

displayMinuteCounts(getMinuteCounts());

In short: solve your problem by factoring your program into methods each of which does one thing well, and does not attempt to do anything else.

Upvotes: 1

Related Questions