Tia Rojas
Tia Rojas

Reputation: 37

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

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

Upvotes: 2

Views: 168

Answers (2)

Pedro A
Pedro A

Reputation: 4323

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.

Upvotes: 2

Eugene
Eugene

Reputation: 120858

Take the range in half and multiply by two:

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

Upvotes: 2

Related Questions