I am doing a question in CodeWar and I had encountered a few problems. The question basically accepts a Boolean array to count the number of sheep (true = add 1 to sumOfSheep, false does not add 1 to sum). This is the input and my code.
Boolean[] array1 = {true, true, true, false,
true, true, true, true ,
true, false, true, false,
true, false, false, true ,
true, true, true, true ,
false, false, true, null };
public class Counter {
public int countSheeps(Boolean[] arrayOfSheeps) {
int sumOfSheep = 0;
for(Boolean sheep:arrayOfSheeps){
if(sheep){
sumOfSheep++;
}
else if(sheep == null){
continue;
}
}
return sumOfSheep;
}
}
After running this code, it will return a NullPointerException. I have tried to print out every element in the array and I noticed that it will crash when it encounters a null value.
if(sheep){
sum++;
System.out.print(sheep);
System.out.println(" Good");
}
else if(sheep == null){
System.out.println("Bad");
continue;
}
The program won't crash if I change the if statement's condition to if(sheep != null && sheep)
. Can I know why is this happening??