0

这就是我在我的数组中随机选择一个元素的方法中的内容,但是我不确定它为什么不起作用,我觉得我已经尝试了所有的写法,任何想法。

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

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

    if (x != null){  

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

    }

  return book;    
}
4

3 回答 3

1

你解释事情的方式让我觉得有几个概念以某种方式交叉。我假设这本书是一些(二维)Seat 对象数组,您想从中选择一个随机对象。为此,您需要为数组的每个维度指定一个随机选择:

// 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. 您绝对应该在进入循环之前测试是否还有未预订的座位,否则它将无限旋转。

因此,实施更智能的选择例程可能是一个好主意,例如通过随机选择一排和一个座位并从那里开始搜索,直到遇到第一个空闲座位,但对于第一步,这应该做得很好。

我希望这是您想要实现的目标,如果不能随意发表评论并让我更正和适应。

于 2012-10-28T23:31:09.733 回答
0

(Math.random()*x.length)Floor表达式返回的数字。

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

目前,您正在尝试使用浮点数为数组下标。

于 2012-10-28T23:21:26.327 回答
0

另一个答案将完全有效,但是如果您不想进行所有数学运算,这是使用Random.nextInt()的另一种方法:

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

它使用java.util.Random,所以如果你这样做,请确保你导入它。

于 2012-10-28T23:24:13.460 回答