0

I've searched all over in the last couple hours and I just can't get a simple counter going in Java! I tried AtomicInteger and it's getAndIncrement() method but that didn't work.

Basically I have a for loop, and within that an if statement, I want an int to be incremented by 1 everytime in the for loop the if statement equates to true. And then after the for loop, return the int.

The int doesn't increment.

Help!

Edit - It's on Eclipse for Android:

public int markTest(Map<Long, String> selectedAnswers,
            Map<Long, String> correctAnswers) {
        int mark = 0;
        for (long i = 1; i <= selectedAnswers.size(); i++) {

            String userSelection = selectedAnswers.get(i).toString();
            if (userSelection == correctAnswers.get(i))
                mark++;
        }

        return mark;
    }
Omair Vaiyani
  • 552
  • 7
  • 28

2 Answers2

2

The correct way to check string equality is to use String.equals() instead of equality == operator.

if (userSelection.equals(correctAnswers.get(i))) {

Since, your if condition is failing all the time mark is not getting incremented. Also, there's no need for toString() since selectedAnswers is already of type Map<Long, String>

String userSelection = selectedAnswers.get(i);

References:
Java String.equals versus ==
How do I compare strings in Java?

Community
  • 1
  • 1
Ravi K Thapliyal
  • 51,095
  • 9
  • 76
  • 89
0

after the if statement write count++ example and don't forget to initialize the count outside the loop count=0 or what ever number you want to start with.

if(condition) count++;

return count;

Ivan_Stepul
  • 229
  • 1
  • 2
  • 8