【问题标题】:Math.random range using the size of an arraylist使用数组列表大小的 Math.random 范围
【发布时间】:2013-10-05 13:33:13
【问题描述】:
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 中的第一项。我该怎么做才能解决这个问题?

【问题讨论】:

    标签: java random arraylist


    【解决方案1】:

    试试这个:

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

    问题是您在将 math.random 值相乘之前将其转换为 int。强制转换具有更高的运算符优先级(完整列表参见http://introcs.cs.princeton.edu/java/11precedence/

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

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

    【讨论】:

    • 非常感谢。这完美地工作。我正在拔头发,试图弄清楚我犯了什么愚蠢的错误。
    【解决方案2】:

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

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

    应该可以正常工作

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 2017-12-03
      • 2016-10-05
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      相关资源
      最近更新 更多