Write an application to simulate the rolling of two dice.
Question #39658, Programming, Java | JSF | JSP
class PairOfDice {
private Die die1;
private Die die2;
public PairOfDice(Die die1, Die die2) {
this.die1 = die1;
this.die2 = die2;
}
public PairOfDice(int sides) {
die1 = new Die(sides);
die2 = new Die(sides);
}
public int rollDice() {
return die1.rollDie() + die2.rollDie();
}
}
class Die {
private int sides;
public Die(int sides) {
this.sides = sides;
}
public int rollDie() {
return 1 + (int) (Math.random() * sides);
}
}
public class DiceDriver {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String option = "y";
while (option.equals("y")) {
try {
System.out.println("Input number in range 4-20");
int sides = input.nextInt();
input.nextLine();
if (sides < 4 || sides > 20) {
throw new OutOfBoundsException();
}
Die die1 = new Die(sides);
Die die2 = new Die(sides);
PairOfDice dice = new PairOfDice(die1, die2);
int sum = dice.rollDice();
System.out.println("Sum: " + sum);
if (sum == 2) {
System.out.println("Snake eyes!");
}
if (sum == 7) {
System.out.println("Craps!");
}
if (sum == 12) {
System.out.println("Box cars!");
}
System.out.println("Do you want to play more?");
option = input.nextLine().toLowerCase();
} catch (InputMismatchException ime) {
System.out.println("Incorect format number");
input.nextLine();
} catch (OutOfBoundsException oe) {
System.out.println("Please input number in range 4-20");
}
}
}
}
class OutOfBoundsException extends Exception {
public OutOfBoundsException() {
super();
}
}
Need a fast expert's response?
Submit order
and get a quick answer at the best price
for any assignment or question with DETAILED EXPLANATIONS!
Learn more about our help with Assignments:
JavaJSPJSF