How do I define and initialize a variable that generates random integers from 2 to 20 inclusive?

Viewed 64

I need to create two different dice in Java. The first one (dice1) has random integer values from 1 to 10 inclusive. The second dice (dice2) should have even numbers from 2 to 20 inclusive. I was able to successfully code for dice1 but cannot figure out how to declare and initialize dice2. Below is the code I wrote for dice1. How would I go about coding for dice 2?

int dice1 = (int)Math.floor(Math.random()*(10-1+1)+1);
2 Answers

Take the range in half and multiply by two:

int dice2 = ThreadLocalRandom.current().nextInt(1, 11) << 1

If you already have dice to roll from 1 to 10, just roll it and multiply the result by 2. Then you'll have dice for even numbers from 2 to 20.

Related