-1

I understand I have to use the random method but thats where my understanding ends

  • a random real number from 0-1? How do you think that would map to 6 equal possibilities? – ergonaut Oct 03 '15 at 23:27
  • 3
    Possible duplicate of [How can i make a "dice" that randomly generates a number 1-6 EACH time it is used?](http://stackoverflow.com/questions/8410455/how-can-i-make-a-dice-that-randomly-generates-a-number-1-6-each-time-it-is-use) – Mick Mnemonic Oct 03 '15 at 23:29

1 Answers1

1

The Random class has a nextInt(int) method that makes it easy to select a value:

Random random = new Random(); // ... or possibly reuse an existing Random
int side = random.nextInt(6); // resulting side is in 0...5

In many other languages, there is only a method to obtain an evenly-distributed number between 0 and 1. In those cases, multiplying this value by the size of the range will give you an evenly distributed number in the desired range, and then you simply add an offset to shift the result into the range in question. This is the same principle by which the internals of nextInt() operates.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200