192k views
5 votes
Implement a class called PairOfDice, composed of two Die objects. Include methods to set and get the individual die values, a method to roll the dice, and a method that returns the current sum of the two die values.Create a driver class called RollingDice2 to instantiate and use a PairOfDice object. The final program should have a main method or a test class.

User Rufanov
by
5.4k points

1 Answer

7 votes

Answer:

The java program to implement the given scenario is shown below. Comments are included at all places.

import java.util.*;

class PairOfDice

{

//variables to hold all required values

static int dice1, dice2;

static int min=1;

static int max=6;

//setter for two dice values

static void setFirstValue(int d1)

{

dice1 = d1;

}

static void setSecondValue(int d2)

{

dice2 = d2;

}

//getters for two dice values

static int getFirstValue()

{

return dice1;

}

static int getSecondValue()

{

return dice2;

}

//method to roll dice using random() method

static void rollDice()

{

int d1 =(int) ( (Math.random() * ((max - min) + 1)) + min);

int d2 = (int)( (Math.random() * ((max - min) + 1)) + min);

//randomly generated values passed to the setters

setFirstValue(d1);

setSecondValue(d2);

}

//method to return sum of two dice values

static int sumDice()

{

rollDice();

//getters called to get the two dice values to compute their sum

return getFirstValue() + getSecondValue();

//return dice1+dice2;

}

}

public class RollingDice2

{

public static void main(String[] args)

{

//first object

PairOfDice ob1 = new PairOfDice();

System.out.println("First object: Sum of two die values is " +ob1.sumDice());

//second object

PairOfDice ob2 = new PairOfDice();

System.out.println("Second object: Sum of two die values is " +ob2.sumDice());

}

}

OUTPUT

First object: Sum of two die values is 8

Second object: Sum of two die values is 6

Step-by-step explanation:

1. All the variables and methods are declared as static.

2. Inside the rollDice() method, the values of both the dice are generated randomly using random() method.

3. The generated values are passed to the setter methods.

4. Inside the sumDice() method, first, rollDice() method is called which generates dice values and calls setter methods.

5. Next, getter methods are called for obtaining the dice values. These values are added and returned without using any variable.

6. Inside main(), two objects of the class PairOfDice are created and respective sum of dice values are displayed to the user.

User AHunter
by
5.7k points