【问题标题】:If statement on array数组上的 if 语句
【发布时间】:2013-01-06 17:02:32
【问题描述】:

我有以下 java 位

if(board[i][col].equals(true))
    return false

但是,当我编译它时,我收到以下错误 - “int cannot be dereferenced” - 谁能解释一下这是什么意思?

谢谢!

【问题讨论】:

标签: java primitive-types comparison-operators


【解决方案1】:

它可能是一个原始类型数组 (int?)。

使用==,就可以了。但如果是 int,请确保不要将其与 true 进行比较:Java 是强类型的。

当您想测试两个不同对象是否相等时,您可以使用equals

【讨论】:

  • 确实,我认为很可能是这种情况...抱歉,我是 Java 新手,习惯了不太严格的语言 :) 感谢您的帮助!
  • 嗯好吧,这很奇怪,数组声明为:boolean[][] chessboard;棋盘=新布尔[行][列];并检索为: boolean[][] board = Initiative.getChessboard();但我仍然得到同样的错误......
【解决方案2】:
    // Assuming
    int[][] board = new int[ROWS][COLS];

    // In other languages, such as C and C++, an integer != 0 evaluates to true
    // if(board[i][col]) //this wont work, because Java is strongly typed.

    // You'd need to do an explicit comparison, which evaluates to a boolean
    // for the same behavior.
    // Primitives don't have methods and need none for direct comparison:
    if (board[i][col] != 0)
        return false;

    // If you expect the value of true to be 1:
    if (board[i][col] == 1)
        return false;

    // Assuming
    boolean[][] board = new boolean[ROWS][COLS];

    if (board[i][col] == true)
        return false;

    // short:
    if (board[i][col])
        return false;

    // in contrast
    if (board[i][col] == false)
        return false;

    // should be done using the logical complement operator (NOT)
    if (!board[i][col])
        return false;

【讨论】:

  • if(board[i][col] == true) ==> if(board[i][col]) 更加标准和可读。
  • 这是关于比较的,但这确实是一个人应该这样做的方式。固定。
【解决方案3】:

带有以下声明:

boolean[][] board = initiate.getChessboard();

您需要使用以下条件:

if(board[i][col] == true)
    return false;

也可以这样写:

if(board[i][col])
    return false;

这是因为equals 只适用于对象,而 boolean 不是对象,它是原始类型。

【讨论】:

    【解决方案4】:
    if(board[i][col])
        return false
    

    如果数组为boolean[][],则与== 进行比较。并且比较== true也可以省略。

    【讨论】:

      【解决方案5】:

      如果boardboolean 原语的数组,请使用

      if(board[i][col] == true)
        return false;
      

      if (board[i][col]) return false;
      

      return !board[i][col];
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多