Free Response Practice Question (with solution)- Dice Game Project
<-- Back to Triangle Project | Next to Mixed Number Project --> |
Dice Game Project
Part 1: Dice.java
Write the complete class definition for the Dice class. The Dice class consists of the following:
- int value: the current value of the dice.
- The default constructor initializes value to zero.
Additionally, the Dice class consists of only one method, rollDice(), that returns a random integer between 1 to 6. The class should not have any accessor methods.
Part 2: DiceGame.java
Write the complete class definition for the DiceGame class. The DiceGame class consists of the following:
- Dice dice1: a dice object of the Dice class.
- Dice dice2: another dice object of the Dice class.
- The default constructor that initializes both the Dice objects with default values.
Additionally, the class consists of a method named playGame() that does the following:
- invokes the method rollDice() of the Dice class on each of the dice objects that it has.
- Prints the message that the user wins the game, if the sum of the result on the two dices is equal to or greater than 8, or else otherwise.
Part 3: DiceGameRunner.java
Write the complete class definition for the DiceGameRunner class. The DiceGameRunner class creates an object of the DiceGame class and invokes the playGame() method on it, in its main() method.
Solution:
Part 1: Dice.java
public class Dice { int value; public Dice() { value=0; } public int rollDice() { value = (int) (Math.random()*6)+1; return value; } }
Part 2:DiceGame.java
public class DiceGame { Dice dice1; Dice dice2; public DiceGame() { dice1 = new Dice(); dice2 = new Dice(); } public void playGame() { int roll1= dice1.rollDice(); int roll2= dice2.rollDice(); System.out.println("Result of the rollDice() on dice1: "+ roll1); System.out.println("Result of the rollDice() on dice2: "+ roll2); if ((roll1+ roll2) >=8) System.out.println("Congratulations, You WIN!"); else System.out.println("Oops, You loose..."); } }
Part 3: DiceGameRunner.java
public class DiceGameRunner { public static void main(String args[]) { DiceGame game = new DiceGame(); game.playGame(); } }
Java project files (with Runner code):
<-- Back to Triangle Project | Next to Mixed Number Project --> |