Java: Random Numbers
To create random numbers in java, we will need to import another java utilities file, this time one called appropriately random.
import java.util.Random;
Now we have to create a new object for our random class, im going to call mine dice, as I want to make a dice.
Random dice = new Random();
Now we use "dice" to generate some random numbers, to do this we have to use the "nextInt" method:
dice.nextInt(NUMBER OF OPTIONS);
Remember computers always count from 0, so if you you go ahead and put six in there you will get the numbers 0-5 instead of what we want which is 1-6. All we have to do to get 1-6 is increment every random number, we can easily do this just with a simple mathematical operator.
Here is the complete dice rolling code:
int DiceRoll;
Random dice = new Random();
DiceRoll = 1 + dice.nextInt(6);
System.out.println(DiceRoll);
Back to Java

