Search code examples
javafor-loopif-statementcountcounter

why won't my counter count properly ? it adds +1 although my if statement isnt filled


So my counter is supposed to not count +1 for the string ":DD" that's why I wrote that only if the length of my string is 2 the counter should add +1. But it adds +1 although the string length is 3. Why is that?

P.S.: I've put length() <=3 in the first if statement, for another else if that comes after the 2nd if statement.

int counter = 0;
String tgt = ":DD";

for (int i = 0; i < a.size(); i++) {
    if (tgt.length() <= 3 && tgt.charAt(0) == ':' || tgt.charAt(0) == ';') {
        if (tgt.length() == 2 &&  
            tgt.charAt(1) == ')' || tgt.charAt(1) == 'D') {
                counter += 1;
        }
    }
}

Solution

  • The && operator has higher precedence than ||, messing up your intended logic.

    The Java operators page lists Java operators in order of precedence.

    Because of this, it's as if parentheses are around the two && operands:

    if ((tgt.length() <= 3 && tgt.charAt(0) == ':') || tgt.charAt(0) == ';')
    {
        if ((tgt.length() == 2 &&  tgt.charAt(1) == ')') || tgt.charAt(1) == 'D')
    

    In the second if condition, the && may return false, but the second (index 1) character is 'D', so the whole condition is true and your counter gets updated.

    Place explicit parentheses around your || operands, which is what I think you intended.

    if (tgt.length() <= 3 && (tgt.charAt(0) == ':' || tgt.charAt(0) == ';'))
    {
        if (tgt.length() == 2 && (tgt.charAt(1) == ')' || tgt.charAt(1) == 'D'))