你解釋事物的方式讓我覺得有些概念在某種程度上被交叉連接了。我假設這本書是一些(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
但是像這樣的全隨機選擇有幾個缺點:
- 的選擇是隨機的,你可以反覆落在已經預訂座位,且在此增量的機會隨着已經預訂的座位數量減少。但即使只有少量預訂座位,您可能會非常不幸,並看到環路旋轉數十次纔會撞到未預訂的座位。
- 您應該絕對測試在進入循環之前是否還有未預訂座位,否則它將無限期旋轉。
因此它可能是實現一個更聰明的選擇程序,例如通過隨機選擇一個行和座位,遇到第一個免費座位,直到從那裏開始尋找一個好主意,但是對於第一步這一個應該做的正好。
我希望這是你想達到的目的,如果不是隨意發表評論,並讓我糾正和適應。
來源
2012-10-28 23:31:09
fvu
你的'書籍'是座位[] []'但你的功能有'座位'的返回類型... – Eric