How to Make a Dice Roll in Java?

In this tutorial, we will simulate dice rolls with different ways such as Math.random and Random class. And we will give examples for rolling multiple dices with for loop and while loop. And final example will be about storing dice results in array of integers

How to Make a Dice Roll in Java?

Example 1: Rolling 1 dice with Math.random()

int dice = (int)(Math.random()*6)+1;
System.out.println(dice);
//1 2 3 4 5 or 6

Example 2: Rolling 1 dice with Random()

Hint: new Random().nextInt((max - min) + 1) + min

Note: You need to import import java.util.Random class

int dice = new Random().nextInt(6)  + 1;
System.out.println(dice);
//1 2 3 4 5 or 6

Example 3: Rolling 10 dices with for loop

for (int i=1; i<=10; i++)
{
	int dice = new Random().nextInt(6)  + 1;
	System.out.print(dice+" ");
	//1 4 5 1 5 4 4 2 6 6 
}

Example 4: Rolling 10 dices with while loop

int count=0;
while (count<10)
{
	int dice = new Random().nextInt(6) + 1;
	System.out.print(dice+" ");
	count++; 
}
//1 1 2 5 6 2 5 2 4 3 

Example 5: Rolling 10 dices and storing dice results in array

int[] dices = new int[10];
int count=0;
while (count<10)
{
	dices[count]=new Random().nextInt(6) + 1;
	count++; 
}
System.out.println(Arrays.toString(dices));
//[5, 3, 1, 1, 3, 2, 6, 4, 2, 6]