Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
115 views
in Technique[技术] by (71.8m points)

java - How to access a random generated integer from other class without generating other random number

I have two classes

Class 1

public class Random {

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

And Class 2

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

    public static void main(String[] args) {

            System.out.println(generatedNumber);
    }
}

Every time I try to access the generatedNumber variable of Class 2 from a third Class, the number I get is different and not the one received in Class 2.

My question is how I can make the number generated in Class 2 persist to be able to call it from other Classes and that it is always the same number generated in Class 2.

question from:https://stackoverflow.com/questions/65938351/how-to-access-a-random-generated-integer-from-other-class-without-generating-oth

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You asked me to show you:

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;
    }

}

When you need to retrieve the number, use the getFixRandom() method.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...