First, write a class called Dice that simulates a single dice. The Dice class sh
ID: 3542998 • Letter: F
Question
First, write a class called Dice that simulates a single dice. The Dice class should have the
following fields and methods (with these names and caps):
Field/Method Description
Value - The Value field holds the value of the dice
SetValue - The setValue method stores a value in the Value field
GetValue - The getValue method returns the value of the dice
Roll - The Roll method that generates a random number in the range of 1 through 6 for the value of the die
OutputDice - The OutputDice method output the value of the dice as text (e.g. ONE, TWO, THREE, FOUR, FIVE, and SIX)
DrawDice - The DrawDice method draw the dice/an image of the dice (on more than one line using ASCII characters and/or symbols) in the console window (not a dialog box); This method is optional (for 5 extra credit points)
Once you have designed the class, design a program (DiceDemo) that creates two objects/instances of the Dice class to simulate a pair of dice. The program should simulate the rolling of the 2 dice and display their values (using the OutputDice method, and, if you did the extra credit, also using the DrawDice method).
Explanation / Answer
import java.util.Random;
public class Dice
{
public int randomValue;
int value;
public static void main(String args[])
{
Dice d1=new Dice();
d1.setValue();
d1.OutputDice();
}
public void setValue()
{
this.value=this.roll();
}
public int getValue()
{
return this.value;
}
public int roll()
{
int randomInt=((int)(Math.random()*100));
while(randomInt>6)
{
randomInt=(int)randomInt/6;
}
return randomInt;
}
public void OutputDice()
{
System.out.println(this.value);
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.