【问题标题】:Setting a public int to a random number将公共 int 设置为随机数
【发布时间】: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 类。

标签: java random int


【解决方案1】:

你可以使用static initialization block,比如

public static int response;
static {
    Random rand = new Random();
    response = rand.nextInt(6) + 1;
}

【讨论】:

    【解决方案2】:

    字段rand 必须在静态上下文中定义,response 才能引用该字段。

    要么使用这个:

    public static int response = new Random().nextInt(6) + 1;
    

    或者只是对于随机数可以使用 Math 类中的静态 random() 方法。

    public static int response = 1 + (int)(6 * Math.random())
    

    如果您需要创建其他随机数,那么您可以创建一个私有的rand 字段。

    private final static Random rand = new Random();
    public static int response = rand.nextInt(6) + 1;
    

    【讨论】:

      【解决方案3】:

      您可以使用ThreadLocalRandom class

      import java.util.concurrent.ThreadLocalRandom;

      public static int response = ThreadLocalRandom.current().nextInt(6) + 1;
      

      【讨论】:

        猜你喜欢
        • 2012-01-15
        • 1970-01-01
        • 1970-01-01
        • 2015-06-09
        • 1970-01-01
        • 1970-01-01
        • 2016-01-14
        • 2013-06-12
        • 1970-01-01
        相关资源
        最近更新 更多