2012-10-28 18 views
0

這是我在我的方法中隨機選擇數組中的一個元素,但我不確定它爲什麼不是工作,我覺得我已經嘗試了寫它的任何方式,任何想法。試圖從數組中獲得一個隨機元素,以便我可以將其標記爲「已預訂」

public static Seat BookSeat(Seat[][] x){ 

    Seat[][] book = new Seat[12][23]; 

    if (x != null){ 

     book = x[(Math.random()*x.length)]; 

    } 

    return book;  
} 
+1

你的'書籍'是座位[] []'但你的功能有'座位'的返回類型... – Eric

回答

1

你解釋事物的方式讓我覺得有些概念在某種程度上被交叉連接了。我假設這本書是一些(2維)座位對象的數組,您想從中隨機選擇一個。爲了做到這一點,你需要指定一個隨機選擇的數組的每個維度:

// this should be declared elsewhere because if it's local to bookSeat it will be lost 
// and reinitialized upon each call to bookSeat 
Seat[][] book = new Seat[12][23]; 

// and this is how, after previous declaration, the function will be called 
Seat theBookedSeat = bookSeat(book); 

// Okay, now we have selected a random seat, mark it as booked, assuming Seat has a 
// method called book: 
theBookedSeat.book(); 


// and this is the modified function. Note also that function in Java by convention 
// start with a lowercase letter. 
public static Seat bookSeat(Seat[][] x){ 
    if (x != null){ 
     // using Random as shown by chm052 
     Random r = new Random(); 
     // need to pick a random one in each dimension 
     book = x[r.nextInt(x.length)][r.nextInt(x[0].length)]; 
    } 
    return book; 
} 

你也應該整合測試,以檢查所選擇的座位是否已經預訂和重複選擇:

 do { 
      // need to pick a random one in each dimension 
      book = x[r.nextInt(x.length)][r.nextInt(x[0].length)]; 
     while (book.isBooked()); // assuming a getter for a boolean indicating 
           // whether the seat is booked or not 

但是像這樣的全隨機選擇有幾個缺點:

  1. 的選擇是隨機的,你可以反覆落在已經預訂座位,且在此增量的機會隨着已經預訂的座位數量減少。但即使只有少量預訂座位,您可能會非常不幸,並看到環路旋轉數十次纔會撞到未預訂的座位。
  2. 您應該絕對測試在進入循環之前是否還有未預訂座位,否則它將無限期旋轉。

因此它可能是實現一個更聰明的選擇程序,例如通過隨機選擇一個行和座位,遇到第一個免費座位,直到從那裏開始尋找一個好主意,但是對於第一步這一個應該做的正好。

我希望這是你想達到的目的,如果不是隨意發表評論,並讓我糾正和適應。

+0

在我的主類中,我有一個2d的數組,創建了Seat類型,所以我想要一個方法來調用它,使我可以從該數組中選擇一個隨機元素,然後我可以將該元素標記爲「已預訂」。 我在方法裏面創建了'Seat [] [] book',因爲我不知道如何在方法內部不創建數組的情況下返回方法的值。 – user1719605

+0

這正是我描述的場景 - 座椅[] []書=新座椅[12] [23];'是在你的主要,然後調用bookSeat返回1個座椅對象陣列。讓我再補充一些解釋。 – fvu

+0

噢,我覺得我的工作方法似乎現在運行,我需要創建一個座位對象來返回數據,出於某種原因,我認爲我不得不創建一個數組,我認爲現在所有的工作。非常感謝你的幫助。^^ – user1719605

0

(Math.random()*x.length)表達式返回的數字放在最下面。

Math.floor(Math.random()*x.length); 

此刻,您正在嘗試使用浮點數爲該數組下標。

0

對方回答會完全工作,但這裏是用Random.nextInt()做的另一種方式,如果你不想要做的身邊所有的mathing:

Random r = new Random(); 
book = x[r.nextInt(x.length)]; 

它採用java.util.Random,所以一定要確保你輸入,如果你這樣做。

相關問題