Home > Software engineering >  check if all number from 1-9 are in 3x3 array
check if all number from 1-9 are in 3x3 array

Time:12-09

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

CodePudding user response:

The problem is due to your if statements :

If (t=false) break;

The issue is that you only have a single =, which makes that clause an assignment, the value of which is the value being assigned (in this case, false). This results in the breaks never being executed, so the loops always complete - and the result of that is that the counts will ALWAYS find 9 numbers

Simple solution is to either use ==, or better to use the ! operator (oh, and change the name to something immediately understandable ), eg :

if (!missing) break;

CodePudding user response:

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