如何检查二维数组中的一个整数是否等于另一个整数



如何检查2D数组中的一个整数是否等于另一个整数?

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

我正试图将整数";a";从名为";int[][]板";用其它变量(b,c,d,e,f,g,h,i(检查是否";a";等于它们中的任何一个。

我试图通过写下以下内容来解决这个问题:

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

操作||(称为"或"(似乎不能用于比较整数。我该如何解决该问题?

您可以做的是遍历2d数组,并使用布尔值检查它是否包含您正在比较的元素。您可以编写如下内容:

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

在这行代码之后,你可以用代码随心所欲

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

然而,如果您尝试比较变量";a";因为数组的第一个元素是它自己。对于这种情况,您可以做以下操作:

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
}

希望它能有所帮助。

为了解决您的尝试,正确的语法应该是

CCD_ 2。

但是,根据您的用例,可能建议在数组上循环。

我会通过编写一个通用函数来解决这个问题,该函数检查数组中特定位置的值是否出现在其他位置:

static boolean isDuplicate(int[][] arr, int row, int col)
{
for(int r=0; r<arr.length; r++)
{
for(int c=0; c<arr[r].length; c++)
{
if(arr[r][c] == arr[row][col] && (r != row || c != col))
{
return true;
}
}
}
return false;
}

然后你可以做这样的事情:

int[][] board = {{a,b,c}, {d,e,f}, {g,h,i};
boolean duplicateA = isDuplicate(board, 0, 0);

最新更新