Reginald
Reginald

Reputation: 818

Java Treemap not incrementing properly

I'm currently trying to write an error logging utility for a program in work that automates tasks carried out by other products in multiple steps(It's Selenium, but I don't think that's relevant).

When a step fails for a particular task, I want to identify the step, and how many times it fails throughout a particular task (many steps are generic and repeated such as "Send Message TO X", "Update X Log" etc.)

The issue I'm facing is that when it counts an error, it's not incrementing properly. If a step fails once, it will pick it up as a count of 1. If a step fails twice, the count will remain on 1. If it fails 3 times the count will then increment to two, if 4 times it will increment to 3, and so on.

This means that if a step fails more than once my count is always off by one.
The code I'm using for this particular job is:

int count = map.containsKey(word) ? map.get(word) : 0;
if(word.startsWith("api") && line.contains(date.toString())){
    if (!map.containsKey(word)) {
        map.put(word, 1);
    } else {
        map.put(word, count + 1);
    }
}

Any pointers at all would be greatly appreciated. Regards, Reg.

Upvotes: 2

Views: 105

Answers (1)

Keerthivasan
Keerthivasan

Reputation: 12880

You should try changing it to

if (!map.containsKey(word)) {
        map.put(word, 1);
      } else {
        map.put(word, map.get(word) + 1);
      }

The variable count value may be outdated during the execution. This kind of issues are best suitable for debugging. Try to track the value of count step by step, that will help you nail down this issue.

Upvotes: 1

Related Questions