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:


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:


Additionally, the class consists of a method named playGame() that does the following:


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 -->