【问题标题】:How to compare the values with a 2D array elements?如何将值与二维数组元素进行比较?
【发布时间】:2020-12-16 16:50:49
【问题描述】:

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

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"){ 返回错误:

incompatable types: java.langString cannot be converted to boolean

这是我要比较的数组:

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

因此,例如,我想获取行和列的用户输入,假设这些是第 1 行第 1 列。然后我想将这两个与数组进行比较,看看 board[1][1] = "W" 是否无效移动其他地方一块。 任何帮助表示赞赏,谢谢。

【问题讨论】:

    标签: java arrays multidimensional-array comparison


    【解决方案1】:

    声明

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

    意思是:

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

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

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

    【讨论】:

      【解决方案2】:

      代替

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

      应该是

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

      【讨论】:

        猜你喜欢
        • 2020-03-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-22
        • 2018-06-28
        • 2015-06-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多