IPiiro IPiiro - 1 month ago 8
Java Question

Boolean method doesn't work like it should

So I really don't get what I did wrong here. The method should take a boolean array and check if all elements are true, if one is false it should return false.

public static boolean nvm(boolean[] con){
boolean c = true;

for(int i = 0; i<con.length ; i++){
if(and(con[i],con[i++]) == false){
c = false;
}
}
return c;
}


The
and
check two booleans, if they're both true it returns true, otherwhise false. I have already tested
and
, but its working fine.

Wrote the post on my mobile, so I hope it doesn't looks weird. Thankful for any help.

Max Max
Answer Source

Problem is in this line:

if(and(con[i],con[i++]) == false){

Particularly with i++ part. i++ actually increases i, so you may skip some array elements and get a wrong result. Use i+1 instead, which would leave i unchanged.

Also, you can simplify your code like this:

public static boolean nvm(boolean[] con) {
    for(int i = 0; i < con.length ; i++) {
        if (!con[i]) return false;
    }

    return true;
}