Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

JAVA DICE ROLL GAME! Use for loops and arrays to create the ultimate dice game!

ID: 3703971 • Letter: J

Question

JAVA DICE ROLL GAME!

Use for loops and arrays to create the ultimate dice game! You must use two java classes. The first, use a method to generate a value based on the number of sides, a method that rolls one to three dice that results in a total and assigned to the array. Then one more to print the array that displays all of your rolls. Then you must create a tester class to ask for the number of rolls and number of dice. And then call your three previous methods. Your output should be similar to:

How many dice? 1-3: 3

Number of rolls: 3

Roll 1: 7

Roll 2: 9

Roll 3: 14

Roll the number: Times:

3 0

4 2

5 0

7 1

etc.

Explanation / Answer

DiceTester.java

import java.util.Scanner;

public class DiceTester {

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("How many dice? 1-3: ");

int numberOfDices = scan.nextInt();

System.out.println("Number of rolls: ");

int numberOfRolls = scan.nextInt();

Dice d = new Dice(numberOfRolls,numberOfDices);

for(int i=0;i<numberOfRolls;i++) {

d.roll();

}

d.print();

}

}

Dice.java

import java.util.Random;

public class Dice {

private int numberOfRolls, numberOfDices;

int a[] = null;

Random r = new Random();

public Dice(int n1, int n2) {

numberOfRolls=n1;

numberOfDices=n2;

a=new int[6*numberOfDices];

}

public void roll() {

int total = 0;

for(int i=0;i<numberOfRolls;i++) {

total+=r.nextInt(6)+1;

}

a[total-numberOfRolls]++;

}

public void print() {

System.out.println("Roll the number Times");

for(int i=0;i<a.length;i++) {

System.out.println(i+numberOfRolls+" "+a[i]);

}

}

}

Output:

How many dice? 1-3:

3

3Number of rolls:  

Roll the number Times

3 0

4 0

5 0

6 0

7 0

8 0

9 1

10 1

11 0

12 0

13 0

14 1

15 0

16 0

17 0

18 0

19 0

20 0