【问题标题】:How to access a random generated integer from other class without generating other random number如何从其他类访问随机生成的整数而不生成其他随机数
【发布时间】:2021-01-28 13:46:24
【问题描述】:

我有两节课

第一类

public class Random {

    public static int random() {
        Random random = new Random();
        return random.nextInt(10);
    }
    public static int number = random();
}

第二类

public class SecondClass {
    
    static int generatedNumber = Random.number;

    public static void main(String[] args) {

            System.out.println(generatedNumber);
    }
}

每次我尝试从第三个 Class 访问 Class 2 的 generatedNumber 变量时,我得到的数字都是不同的,而不是 Class 2 中收到的数字。

我的问题是如何使在 Class 2 中生成的号码保持不变,以便能够从其他 Class 中调用它,并且它始终与 Class 2 中生成的号码相同。

【问题讨论】:

  • 我很困惑......你想要一个随机数,还是总是一样的?
  • 与其称事物为“Class 1/2/third class”,不如直接用它们的名字来称呼它们:Random/FirstClass?令人困惑的是 Class 2 是 FirstClass。另外,请出示第三节课。
  • (如果可能的话,如果您将这些字段设为final,可能会对您的问题有所帮助)。
  • @Stultuske 我想生成一次该随机数,然后从其他类访问它而不再次生成它。
  • 你希望你的随机类做两件事,重复一个旧的随机数和发送一个新的随机数。这意味着您需要两种方法,一种用于检索旧数字,另一种用于生成新的随机数。

标签: java variables random


【解决方案1】:

你让我给你看:

public class FixRandom {

    // Holds the fixed random value.
    private final int fixedValue;

    // Upper bound for the RNG.
    private static final int BOUND = 10;

    // Constructor.
    public FixRandom() {
        // Set the fixed random value.
        Random rand = new Random();
        fixedValue = rand.nextInt(BOUND);
    }

    // Method to access the fixed random value.
    public int getFixRandom() {
        return fixedValue;
    }

}

当需要找回号码时,使用getFixRandom()方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2014-08-22
    • 2020-08-06
    相关资源
    最近更新 更多