【发布时间】:2017-04-20 00:37:04
【问题描述】:
我想将公共 int 设置为随机值。但是,我有一个问题。
public static int response = rand.nextInt(6) + 1;
public static void main(String []args){
Random rand = new Random();
此代码不起作用。我明白了,因为 random 在 main 方法中,公共 int 无法检索 rand。有什么办法可以将公共 int 设置为随机数?
【问题讨论】:
-
为什么不把
response = rand.nextInt(6) + 1;移到main里面rand在范围内? -
或者在另一个之前添加一个
private Random rand = new Random();... -
所以我可以用不同的方法使用它。
-
@Berin,什么“其他”?
-
@TheChosenSnail,请看看我的简单解决方案。您可以使用ThreadLocalRandom 类。