How can one check if an integer is equal to another in a 2D array?

Tags: , ,



How can one check if an integer is equal to another in a 2D array?

int[][] board = new int [3][3];
int a = board[0][0];
int b = board[0][1];
int c = board[0][2];
int d = board[1][0];
int e = board[1][1];
int f = board[1][2];
int g = board[2][0];
int h = board[2][1];
int i = board[2][2];

I am trying to compare the integer “a” from the 2D array named “int[][]board” with the other variables (b, c, d, e, f, g, h, i) to check if “a” is equal to any of them.

I attempted to solve this issue by writing out this:

if (a == (b || c || d || e || f || g || h || i))

It seems like the operation || (known as “or”) cannot be used to compare integers. How can I resolve that issue?

Answer

What you could do is iterate through the 2d array and have a boolean to check if it contains the element you are comparing with you could write something as follows:

    int number = a;
    boolean check = false;
    for(int i = 0; i < 3; i++){ // three since you have 3 rows
        for(int j = 0; j < 3; j++{ // three since you have 3 columns
            if(board[i][j] == number)
                check = true;
        }
    }

after these line of codes, you can progress to do as you please with the code

if(check){
..... // your code goes here
}

However, this will be always true if you try to compare variable “a” since the first element of your array is itself. What you could do for such situtaion is as following:

    int number = a;
    int count = 0;
    for(int i = 0; i < 3; i++){ // three since you have 3 rows
        for(int j = 0; j < 3; j++{ // three since you have 3 columns
            if(board[i][j] == number)
                count++;
        }
    }

    if(count > 1) {
        .... // your code goes here
    }
 

hope it helped.



Source: stackoverflow