0

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
  • 915
  • 10
  • 28
IPiiro
  • 97
  • 1
  • 9

4 Answers4

2

The method should take a boolean array and check if all elements are true

for(int i = 0; i<con.length ; i++){
     if(!con[i]) return false;
}
PeterMmm
  • 24,152
  • 13
  • 73
  • 111
1

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;
}
Max
  • 915
  • 10
  • 28
1

Maybe I'm missing something but

'The method should take a boolean array and check if all elements are true, if one is false it should return false'

can be written as:

boolean[] array;
for(boolean a : array) {
  if(!a) { return false; }
}
return true;
Thomas Jungblut
  • 20,854
  • 6
  • 68
  • 91
1

If you you want to check that all elements are true you can easily simplify your code.

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

I do not see any reason for the "and". I can only see that it may cause you to have an idexoutofboundsexception.

MartinByers
  • 1,240
  • 1
  • 9
  • 15