2013-03-27 38 views
0

我們正在運行棋盤遊戲模擬器,我們需要計算機在陣列(棋盤)中選擇0-5之間的隨機位置(所有這些都完成),我們實現了一個數組player1move,用於存儲計算機的移動但是如果隨機值選擇一個空的位置,我們會打印出「錯誤,請再次移動」,但移動會被添加到movehist數組中,儘管是非法移動。任何人想到解析這個隨機int的好方法?檢查隨機Ints?

int player1move; 
    Random rand1 = new Random(); 
    player1move = rand1.nextInt(6); 
    System.out.println("\nPlayer 1, Your move:"); 

    int h = 0; 
int i = player1move; 
player1array.add(i); 
System.out.println(player1array); 
h = h+1; 
+0

你的描述非常混亂。簡單地選擇*總是*一個非空的正確位置是否可行? – 2013-03-27 14:47:39

回答

0

你可以做的是使用Exceptions來控制你的工作流程。您可以定義一個特定的異常爲你的情況,像EmptyPositionException,並在這種情況下使用它,像這樣:

int player1move; 
Random rand1 = new Random(); 
player1move = rand1.nextInt(6); 
if(isEmptyPosition(player1move){ 
    throw new EmptyPositionException("Error, please move again"); 
} 
System.out.println("\nPlayer 1, Your move:"); 

int h = 0; 
int i = player1move; 
player1array.add(i); 
System.out.println(player1array); 
h = h+1; 

可以改進的代碼顯然進行。這只是給你一個你能做什麼的想法。

當代碼進入if語句並引發異常時,方法中的其餘代碼將不會執行。