(Java Program) write three classes: Die, PairOfDice, and Player. The Die class m
ID: 3595517 • Letter: #
Question
(Java Program) write three classes: Die, PairOfDice, and Player.
The Die class mimics the rolling of a die. Specifically, this class will implement the following methods:
A default constructor initializing the number of sides of a die to 6.
An overloaded constructor that takes an integer number of sides (assume greater than 1).
roll which generates and returns a random number between 1 and the number of sides
(inclusive).
An accessor method to read the value of the face on the die.
A toString method returning the string representation of the face value.
The maximum number of sides should be stored as a private constant in the Die class. Also use the Random classfortherandomnumbergenerator.
The PairOfDice class mimics the rolling of two dice. Specifically, this class will implement the following methods:
roll rolls each die and returns the sum.
An accessor method to read the sum of the dice.
A default constructor that creates and initializes the number of sides of each die to 6.
An overloaded constructor that creates and takes two integer number of sides, one for each die.
Player class implements the main method which creates the dice pair and rolls them several
The
times reporting the results.
Explanation / Answer
Die.java
import java.util.Random;
public class Die {
public Die() {
this(6);
}
public Die(int side) {
this.side = side;
this.roll();
}
private int side;
private int face;
Random rn = new Random();
public int getSide() {
return side;
}
public void setSide(int side) {
this.side = side;
}
public int getFace() {
return face;
}
public void setFace(int face) {
this.face = face;
}
public int roll() {
this.face = rn.nextInt(6) + 1;
return this.face;
}
@Override
public String toString() {
String faceString = "One";
switch(this.face) {
case 2:
faceString = "Two";
break;
case 3:
faceString = "Three";
break;
case 4:
faceString = "Four";
break;
case 5:
faceString = "Five";
break;
case 6:
faceString = "Six";
break;
}
return faceString;
}
}
PairOfDice.java
public class PairOfDice {
private Die d1;
private Die d2;
private int sum;
public PairOfDice() {
this(6);
}
public PairOfDice(int n) {
d1 = new Die(n);
d2 = new Die(n);
}
public int roll() {
this.sum = d1.roll() + d2.roll();
return sum;
}
public int getSum() {
return this.sum;
}
}
Player.java
public class Player {
public static void main(String[] args) {
PairOfDice pd = new PairOfDice();
System.out.println("Roll: " + pd.roll());
System.out.println("Roll: " + pd.roll());
System.out.println("Roll: " + pd.roll());
System.out.println("Roll: " + pd.roll());
System.out.println("Roll: " + pd.roll());
System.out.println("Roll: " + pd.roll());
}
}
Sample execution:
Roll: 3
Roll: 12
Roll: 8
Roll: 8
Roll: 7
Roll: 3
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.