井字游戏的投掷例外

时间:2020-01-29 19:28:58

标签: java

我是编程新手,并且成功制作了一个井字游戏,但我需要抛出一个异常,以使我无法彼此叠放。这就是我所拥有的...

      /**
      Choose a cell for player has won.
      @param r the row number chose
      @param c the column number chose
      @param player the player who choose a position          
      @throws UnavailableCellException is the cell has been occupied (by either player)   
      */

   public void choose(int r, int c, int player){

       this.board[r][c] = player;
       try {
           for(int i = 0; i < board.length; i ++) {
               if (player == i && player == i + 1) {
               throw new UnavailableCellException("That spot is taken!!");
               }
           }
        } catch(UnavailableCellException e) {
           System.out.println("That spot is taken!!");
        }
    }

我不知道如何达到当前和先前的转弯以使它们不相等...

1 个答案:

答案 0 :(得分:1)

您可以使用简单的if()语句来检查是否使用了该单元格。根据结果​​,您可以设置单元格值或抛出UnavailableCellException

public void choose(int r, int c, int player) throws UnavailableCellException
{
    if (this.board[r][c] == 0) { // assuming "0" means "free cell"
        // valid, place it
        this.board[r][c] = player;
    } else {
        // already used, throw exception
        throw new UnavailableCellException("That spot is taken!!");
    }
}

如果UnavailableCellExceptionRuntimeException扩展出来,则方法声明中不需要throws UnavailableCellException部分。