Search code examples
javavariablesmathrandomdice

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

Solution

  • Take the range in half and multiply by two:

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