我想检查棋盘的某些区域是否具有特定的 thePlayer 值。
public boolean diagonal( char[][] theBoard, char thePlayer) {
int x = 0;
while (x <theBoard.length){
if (thePlayer == theBoard[x][x]) {
x++;
}
else {
return false;
}
}
最佳答案
由于您使用的是多维数组,请尝试使用嵌套 for 循环。
public boolean diagonal(char[ ][ ] theBoard, char thePlayer) {
boolean result = false;
int x, y; // These will tell you the coordinates of thePlayer if found on theBoard
for(int i = 0; I < theBoard.length; i++)
for(int j = 0; j < theBoard[i].length; j++)
if (thePlayer == theBoard[i][j]) {
result = true;
// Add if you want to know coordinates of the player
x = i;
y = j;
}
return result;
}
对于多维数组,您需要知道行和列中的值。假设您从 i = 0
开始,如果您放入一个循环并查找 theBoard[i] [i]
,您将查看第 0 行第 0 列,然后您将 1 添加到 i,i++
,现在您正在查看第 1 行第 1 列。您正在跳过其他所有内容。这就是为什么您需要一个嵌套的 for 循环来遍历行和列。
看下面的例子...
0 1 2 3 4 5
0 X X X X X X
1 X X X X X X
2 X X X X X X
3 X X X X X X
4 X X X X X X
5 X X X X X X
如果要检查 thePlayer 是否仅在数组的对角线索引中,可以使用单个 for 循环。
public boolean diagonal(char[ ][ ] theBoard, char thePlayer) {
boolean result = false;
int x; // This will tell you the coordinates of thePlayer if found on theBoard
for(int i = 0; I < theBoard.length; i++)
if (thePlayer == theBoard[i][i]) {
result = true;
// Add if you want to know coordinates of the player
x = i;
}
return result;
}
在我看来,对于这样的事情使用 for 循环更容易。 while 循环本质上是相同的东西,但实现方式不同,但在这种情况下,for 循环看起来更清晰,更容易理解。最后,由您决定哪一个更容易实现。
关于java - 有没有一种方法可以检查数组中的特定点是否具有特定字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36927552/