the method checks if all the numbers from 1-9 are in a given 3x3 array. i keep getting true even when the array doesnt contain all the numbers and has one of the numers twice. where is my error?
public boolean allThere(){
int counter=0;
boolean t;
for(int k=1; k<10;k++) {
t=true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if(arr[i][j]==k){
counter++;
t=false;
}
if(t=false) break;
}
if(t=false) break;
}
}
if(counter==9) return true;
else return false;
}
The problem is an operator =
assigns the value to variable t
Whereas ==
is an equality operator that checks the variable value.
Change it to
if (t == false) break;
You can also use !
not operator
if (!t) break;
You can also see this algorithm implemented in java
public boolean allThere(int[][] arr) {
int[] numbers = new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int value = arr[i][j];
numbers[value-1]--;
}
}
for (int bool: numbers) {
if (bool != 0) {
return false;
}
}
return true;
}