2
public void pickWinner() {
      int last = list.size() - 1;
      int number = (int)Math.random()*last;
      System.out.println("And the winner is...");
      Student winner = list.get(number);
      System.out.println(winner);
}

除了 ArrayList 中的第一项之外,我在生成获胜者时遇到问题。我认为这是 Math.random() 的问题,因为我的 ArrayList 的大小似乎是正确的,但它似乎只生成 0 来获得我的 ArrayList 中的第一项。我能做些什么来解决这个问题?

4

2 回答 2

4

尝试这个:

int number = (int)(Math.random()*last);

问题是您在乘以之前将 math.random 值转换为 int 。演员表具有更高的运算符优先级(有关完整列表,请参阅http://introcs.cs.princeton.edu/java/11precedence/

此外,您的代码永远不会选择列表中的最后一个学生,您不应该 -1 'last' int。

您也可以考虑使用 Random 类,即new java.util.Random().nextInt(list.size());您不必担心强制转换和整数如何四舍五入。如果您需要多次重复使用 Random 实例,您甚至可以重复使用它。

于 2013-10-05T13:43:39.600 回答
1

Math.random()生成 和 之间的0.0数字1.0。您在最后一次乘之前进行整数转换,因此随机数会降至 0,然后整体结果将始终为零。

  int number = (int)(Math.random()*last);

应该可以正常工作

于 2013-10-05T13:44:36.073 回答