Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading