【问题标题】:if-else statements and 2d arraysif-else 语句和二维数组
【发布时间】:2014-11-27 01:31:49
【问题描述】:

我正在编写一个方法,通过返回 true 或 false 来检查跳棋游戏的某些移动是否有效。当我想对角移动(不跳跃)时,我的代码工作正常。但是,当我尝试查看我的一块是否可以跳过另一块时,没有返回任何内容(没有错误,没有正确,没有错误消息,只是空白)。我有一个setLocation 方法,它采用棋盘列、行和棋子颜色的三个参数,将棋子放置在棋盘上的所述位置。

如果我的棋盘上有棋子并且我想查看棋子是否可以跳过相反颜色的棋子,我如何让我的代码返回 true 或 false? curRow 和 curCol 只是该片段所在的当前行和列。 destRow 和 destCol 是我希望我的作品去往的目的地。

这是我的代码:

if (board[curCol][curRow].equals(Piece.WHITE)){
    boolean valid=false;
    if ((curRow+1==destRow&&curCol+1==destCol)&&board[destRow][destCol].equals(Piece.NONE)){
        valid=true;
    }else if ((curRow+1==destRow&&curCol-1==destCol)&&board[destRow][destCol].equals(Piece.NONE)){
        valid=true;
    //jumps up right over piece 
    }else if ((curRow+2==destRow&&curCol+2==destCol)&&board[destRow-1][destCol-1].equals(Piece.BLACK)){
        valid=true;
    //jumps up left over piece
    else if ((curRow+2==destRow&&curCol-2==destCol)&&(board[destRow-1][destCol+1].equals(Piece.BLACK))){
        valid=true;
    }else{
        return valid;
    }
    return valid;
}

【问题讨论】:

  • 如果if语句顶部的条件是true,代码总是会返回一些东西或者抛出异常。所以要么顶部的条件为假,要么抛出异常而你错过了它,或者它返回了一些东西但你错过了。

标签: java if-statement multidimensional-array


【解决方案1】:

首先,Java 不能返回“空白”。如果您的方法(您没有显示其声明)是布尔方法,则它必须返回一个布尔值。

为什么不试试这样的:

private static board Peice[][] = new Peice[][]

private enum Peice{
  BLACK(-1, false),
  BLACK_CROWN(-1, true),
  WHITE(1, false),
  WHITE_CROWN(1, true)

  private int direction;
  private boolean crowned;

  public Peice(int direction, boolean crowned){
    this.direction = direction;
    this.crowned = crowned;
  }

  public boolean isLegal(int curRow, int curCol, int destRow, int destCol){
    //not valid if the spot is occupied or if the  move isn't the same distance each way
    if (board[destRow, destCol] != null) || ((Math.abs(destRow - CurRow) != (Math.abs(destCol - curCol)){
      return false;
    }

    if (abs(destRows - curRows) == 1){
      return (destRow - curRow == direction) || crowned;
    } else if (abs(destRows-curRows) == 2){
      return takeMove(curRow, curCol, destRow, destCol);
    // anything but 1 or 2 moves diagonal is never ok.
    } else{
      return false;
    }
  }

  private boolean takeMove(int curRow, int curCol, int destRow, int destCol)
    if (!isOpponent(board[(curRow + destRow)/2, (curCol + destCol)/2])){
      return false;
    }
    return (destRow - curRow) * direction > 0 || crowned;
  }

  private boolean isOpponent(Peice other){
    return other.direction != this.direction
  }
}

【讨论】:

    猜你喜欢
    • 2016-10-18
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-05
    • 2014-11-11
    相关资源
    最近更新 更多