2013-05-12 60 views
0

我有以下代碼不斷引發異常,直到正確的值被發現

//Querying for move 
     int playerMove = currentPlayer.PlayCard(myBoard); 

     //Making move 
     try { 
      playMove(playerMove, currentPlayer); 
     } 
     catch (IndexOutOfBoundsException e) { 

      System.out.println("Sorry, I don't think you can do that..."); 

     } 

玩家使得需要被關聯到一個ArrayList的索引此舉。現在,我的代碼非常正確地指出了一個無效移動的玩家的例外情況,但我想知道如何修改它,以便玩家不斷被要求採取行動,直到他們有效。

謝謝! :)

+5

您不應該使用e處理無效移動xceptions - 你應該用條件來阻止它們。例外是*特殊*行爲 - 嘗試執行無效移動的玩家並不例外。 – 2013-05-12 12:36:12

+0

爲了多次運行代碼,可以使用for/while循環 – BobTheBuilder 2013-05-12 12:37:00

+0

@AntP它是基於控制檯的。我輸出可用移動列表(即:輸入整數1-5),但如果用戶輸入6,除了拋出異常外,我應該怎麼做? :\ – MrD 2013-05-12 12:38:56

回答

1

一樣簡單蛋糕

while(true){ 
    //Querying for move 
    int playerMove = currentPlayer.PlayCard(myBoard); 

    //Making move 
    try { 
     playMove(playerMove, currentPlayer); 
     break; // break the while loop 
    } catch (IndexOutOfBoundsException e) { 
     System.out.println("Sorry, I don't think you can do that..."); 
    } 
} 
+0

乾杯,這工作! :d – MrD 2013-05-12 12:40:31

5

使用while循環

while(!IsMoveValid) 
{ 
    int playerMove = currentPlayer.PlayCard(myboard); 
    IsMoveValid = CheckMoveValidity(playerMove, myBoard); 
} 
playMove(playerMove, currentPlayer); 

public bool CheckMoveValidity(int move, Board board) 
{ 
    if (move > 0) && (move < board.Length) 
    { 
     return true; 
    } else { 
     return false; 
    } 
    // you could make this helper method shorter by doing 
    // return (move > 0) && (move < board.Length); 
} 

注意,這並不在邏輯使用異常:)