如何压缩由 OR 运算符组成的 if 语句?

How do you compress an if statement comprised of OR operators?

我有一个井字棋盘,在检查胜利条件之前,我先检查存储在棋盘[][] 集合中的对象是否为空。

例如:

if(board[0][j] == null || board[1][j] == null || board[2][j] == null)//and so on
//do something
else
  //proceed with row evaluation

没有进一步压缩这些内容的好方法。但是,如果您主要关心的是可读性,则可以将代码移至私有辅助方法中,并为该方法命名以传达您正在评估的条件。

例如

if (isVictoryCondition(...)) {
    ...
}

...

private boolean isVictoryCondition(...) { /* null check logic goes here */ }

您可以将其命名为 checkForNull(...),或者您可以将其命名为更能描述您在检查这些值是否为 null 时实际查找的内容,例如isVictoryCondition(...)如果这是表示胜利条件。

在您的 Board class 中添加一个方法,例如:

public boolean hasAnyNull() {
   boolean found = false;
   for (int i = 0 ; !found && i < board.width ; i++) {
      for (int j = 0; !found && j < board.height ; j++ {
         if (board[i][j] == null) {
            found = true;
         }
      }
   }
   return found;
}

并测试if (hasAnyNull()) {...}。第一个 null 处的方法 returns,与您的 or 条件完全相同。

如果您愿意,该方法可以将板作为参数。