In: Computer Science
Prepare a class and tester that simulates and tabulates the result of repeatedly throwing two dice. Recall a dice, a six-sided cube with 1 through 6 dots on each side.
Using a now familiar looping user experience, the user enters the number of throws. Then, the system simulates the throws and displays the results using a frequency distribution chart. For instance:
Please, use this statement to get the dice action started!
String[] labels = {"Snake Eyes", "Ace Deuce", "Hard Four", "Fever Five", "Easy Six", "Natural Seven", "Easy Eight", "Nina", "Easy Ten", " Yo-leven", "Boxcars"};
Dice.java
import java.util.Random;
public class Dice {
private String[] labels = {"", "Snake Eyes", "Ace Deuce", "Hard Four",
"Fever Five", "Easy Six", "Natural Seven", "Easy Eight",
"Nina", "Easy Ten", "Yo-leven", "Boxcars"};
int[] diceThrows;
private int numberOfThrows;
// initializing number of throws
public Dice(int numberOfThrows) {
this.numberOfThrows = numberOfThrows;
diceThrows = new int[numberOfThrows];
}
// simulation started
public void simulate() {
// creating random instance
Random rand = new Random();
int min = 1, max = labels.length;
// throwing dice
for(int i=0 ; i<numberOfThrows ; i++) {
int randNum = rand.nextInt(max - min) + min;
diceThrows[i] = randNum;
}
distributionChart();
}
// printing the distribution chart
public void distributionChart() {
System.out.println();
System.out.println("-------- Frequency Distribution ----------");
System.out.println();
// iterating through all the keys and printing each
for(int i=1 ; i<labels.length; i++) {
int count = 0;
String s = "";
for(int j=0 ; j<numberOfThrows ; j++) {
if(i==diceThrows[j]) {
s += "*";
count++;
}
}
System.out.println(justify(labels[i])+"\t"+s);
//System.out.println(justify(labels[i])+"\t"+count);
}
System.out.println();
System.out.println();
}
// justify the spaces for string
public String justify(String s){
int size = 20;
for(int i=s.length() ; i<size ; i++)
s += " ";
return s;
}
}
Tester.java
// Tester.java
import java.util.Scanner;
public class Tester {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
String play="y";
do {
// reading number of throws
System.out.print("Enter number of throws : ");
int numberOfThows = sc.nextInt();
// initializing dice with number of dice
Dice dice = new Dice(numberOfThows);
// starting simulation
dice.simulate();
// asking user to continue the game or not
System.out.print("Do you want to continue (y/n) : ");
play = sc.next();
}while(play.charAt(0)=='y');
sc.close();
}
}
Code
Dice.java
Tester.java
Output