2013-10-05 23 views
1
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中的第一项。我能做些什么来解决这个问题?使用ArrayList大小的Math.random范围

回答

4

试试这个:

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

问题是你乘前正在铸造的Math.random价值为int。演员有更高的运算符优先级(完整列表,请参阅http://introcs.cs.princeton.edu/java/11precedence/

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

您也可以考虑使用Random类,即new java.util.Random().nextInt(list.size());,因此您不必担心剧集以及如何整数。如果需要多次执行,您甚至可以重新使用Random实例。

+0

太谢谢你了。这工作完美。我试图弄清楚我犯了什么愚蠢的错误。 – user1730357

1

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

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

应该工作正常