java - 有没有一种方法可以检查数组中的特定点是否具有特定字符?

标签 java

我想检查棋盘的某些区域是否具有特定的 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/

相关文章:

java - 翻译功能出了什么问题?

java - 如果我们有视频 URL,如何检查视频是否正在播放?

java - 缓存 Controller 响应

java - 如何处理使用 Web Driver 动态生成值的表?

java - Clojure:交叉引用变量、声明和编译错误

java - 在java中重新创建颠倒互联网

Java 图形只覆盖新形状?

java - 在单个 hbox 中为 2 个元素提供单独的对齐方式

java - 打印 Jasper 报告/ireport 份数

java - java 1.8下无法启动eclipse