简体   繁体   中英

Printing random even value between two values using inheritance

I am trying to print a list of random even numbers (5 times) using a bounds. Example being from 0 to 30 (including both those numbers). This is what I have so far (this is in its own class):

public int nextEven(int h){
        int n = rand.nextEven(h) % 2;
        return n;
        }

This is where it would print from my main method:

System.out.println("Random Even:");
    for (int i = 0; i < 5; i++){
        System.out.println(rand.nextEven(30));
    }

When I run the program it gives me an error and I am not quite sure how to solve this. This is an example of the desired output of even numbers from 0 to 30:

4 26 12 10 20

It isn't clear why taking the remainder of 2 would yield an even number. Instead, generate a number in the range 0 to h / 2 and then multiply the result of that by 2 . Like,

public int nextEven(int h){
    int n = ThreadLocalRandom.current().nextInt(1 + (h / 2)); // 0 to (h / 2) inclusive
    return n * 2; // n * 2 is even (or zero).
}

What exactly is rand? Is it the Random class or an instance of your own class? Since you want to do something with inheritance I guess you want to overwrite a method, but if rand is an instance of the java Random class this won't work.

The error probably comes from recursively calling nextEven method forever.

If you could clarify what exactly you want to do?

The mod operator % will give you the remainder of the first value divided by the second.

value % 2

... will return 0 if value is even, or 1 if value is odd.

Since rand is a reference to an instance of the class containing your code, you have an infinite recursion. What you really need is something like:

public int nextEven(int h){
    int evenRandomValue;
    do {
        evenRandomValue = (int)(Math.random() * (h + 1));
    } while(evenRandomValue % 2 == 1);

    return evenRandomValue;
}

I see at least two solutions.

The first one supposes that random + 1 = random . I mean, that if you add or subtract a random number you still get a valid random number. That's why you can use Random class to generate a value in the desired period and then add or subtract one it the number is odd.

The second approach is just to generate an array of even values for the desired period. Then take a random value from this array.

Here is a quite explicit way to achieve this using streams:

List<Integer> myRandomInts = Random.ints(lower, upper + 1)
    .filter(i -> i % 2 == 0)
    .limit(5).boxed()
    .collect(Collectors.toList());

This can be read as 'generate an infinite stream of random numbers between given bounds, filter out odds, take the first 5, turn into Integer objects and then collect into a list.

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