简体   繁体   中英

Single Java Random number trying to get the fixed range

I'm trying to generate a random number generator that has a fixed 1-100 range being int min = 1 and int max = 100 . I managed to get this code so far. Using BlueJ as the environment.

import java.util.Random; 

public class RandomNumber { 
    public static int getRandomNumberInts(int min, int max) { 
        Random random = new Random(); 
        return random.ints(min,(max+1)).findFirst().getAsInt(); 
    }
} 

Is there any other way I can get a fixed number within my range without the need to enter the range myself?

You could pass your bounds to the constructor then the RandomNumber object know them and you can just call your method without parameters. But your method can not be static anymore.

public class RandomNumber {

    private Random random;
    private int minBound;
    private int maxBound;

    public RandomNumber(int minBound, int maxBound) {
        this.random = new Random();
        this.minBound = minBound;
        this.maxBound = maxBound;
    }

    public int getRandomNumberInts() {
        return random.ints(minBound, (maxBound + 1))
                     .findFirst()
                     .getAsInt(); 
    }
}

Then you call it this way

RandomNumber rn = new RandomNumber(1, 100);
System.out.println(rn.getRandomNumberInts());
System.out.println(rn.getRandomNumberInts());    
System.out.println(rn.getRandomNumberInts());    
System.out.println(rn.getRandomNumberInts());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM