0

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?

Bentaye
  • 9,403
  • 5
  • 32
  • 45
jinny
  • 21
  • 1
  • 1
    Where is your code? – lwi Mar 23 '18 at 12:22
  • 1
    you seem to have forgotten to actually post your code. – Zinki Mar 23 '18 at 12:22
  • look at this: https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java – arthur Mar 23 '18 at 12:29
  • 1
    Possible duplicate of [How do I generate random integers within a specific range in Java?](https://stackoverflow.com/questions/363681/how-do-i-generate-random-integers-within-a-specific-range-in-java) – M. Prokhorov Mar 23 '18 at 12:31
  • 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(); } } – jinny Mar 23 '18 at 12:59
  • sorry its a bit messy idk why it wont let me post earlier – jinny Mar 23 '18 at 13:00
  • 1
    what do you meam by `without the need to enter the range myself`? How is your program going to know the range if you don't tell it? – Bentaye Mar 23 '18 at 13:53
  • @Bentaye meaning it will automatically give me a random number when i call the method instead of having to manually fill in the range all the time – jinny Mar 23 '18 at 23:11

1 Answers1

0

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());
Bentaye
  • 9,403
  • 5
  • 32
  • 45