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.