We can use arrays to store multiple values (int, double, String...) in Java. As an example, let's throw 10 dices and store the dice values in an array.
Java Program That Stores Dice Results in Array
Example 1: To make a dice simulator, we can use Math.random() method as shown in this tutorial. To store multiple dice results, let's create an dice array.
int[] dices = new int[10]; for (int i=0;i<dices.length;i++) { dices[i] = (int)(Math.random()*6)+1; System.out.print(dices[i]+" "); }
Console Output:
2 6 5 5 6 1 2 4 1 1
Example 2: Let's determine the size of the array in the program by asking the user how many dice to roll
Scanner scanner = new Scanner(System.in); System.out.print("How many dice do you want to roll? > "); int count = scanner.nextInt(); int[] dices = new int[count]; for (int i=0;i<dices.length;i++) { dices[i] = (int)(Math.random()*6)+1; System.out.print(dices[i]+" "); }
How many dice do you want to roll? > 20 2 2 4 5 4 6 1 3 6 2 4 1 6 2 4 4 4 2 5 1