如何将值与二维数组元素进行比较?

How to compare the values with a 2D array elements?

我正在尝试从扫描仪获取用户输入,然后使用所述值将其与二维数组中的值进行比较

public void valid(int tempRow, int tempCol) {
    if (board[tempRow][tempCol] = "W") {
        display();
    } else {
        System.out.println("Move invalid, try again");
        makeMove();
    }
    setPiece(tempRow, tempCol, "W");
    display();
}

这个if(board[tempRow][tempCol] = "W"){returns错误:

incompatable types: java.langString cannot be converted to boolean

这是我要与之比较的数组:

String[][] board = {
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"},
        {"-", "-", "-", "-", "-", "-", "-", "-"}};

例如,我想获取行和列的用户输入,假设这些是第 1 行第 1 列。然后我想将它们与数组进行比较,看看是否 board[1][1] = "W" 如果它然后无效移动否则放置一块。 感谢任何帮助,谢谢。

而不是

if (board[tempRow][tempCol] = "W")

应该是

if (board[tempRow][tempCol] == "W")

声明

if(board[tempRow][tempCol] = "W")

表示:

  1. 将字符串“W”分配给board[tempRow][tempCol]
  2. 测试结果是否正确。

当然,这是不可能的,因为字符串不是布尔值。

您打算使用 == 而不是 =。但这也是错误的。使用 .equals() 进行字符串比较。