in Chapter 4 you created a Die class from which you could instantiate an object
ID: 3668969 • Letter: I
Question
in Chapter 4 you created a Die class from which you could instantiate an object containing a random value from 1 through 6. You also wrote an application that randomly "throws" two dice and displays their values. Modify the application so it determines whether the two dice are the same, the first has a higher value, or the second has a higher value. Save the application as TwoDice2.java.
public class Die
{
int HIGHEST_DIE_VALUE = 6;
int LOWEST_DIE_VALUE = 1
private int randomValue = ((int)(Math.random() * 100) % HIGHEST_DIE_VALUE +
LOWEST_DIE_VALUE);
public int getRandomValue()
{
return randomValue;
}
public void setRandomValue(int value)
{
randomValue = value;
}
}
public class TwoDice extends Die
{
public static void main(String[] args)
{
Die roller = new Die();
int playerRoll1 = roller.getValue();
int playerRoll2 = roller.getValue();
int playerRoll3 = roller.getValue();
int playerRoll4 = roller.getValue();
System.out.println(" Results ");
System.out.println(" Player1:");
System.out.println("Die 1 rolled a " + playerRoll1);
System.out.println("Die 2 rolled a " + playerRoll2);
System.out.println(" Player2:");
System.out.println("Die 1 rolled a " + playerRoll3);
System.out.println("Die 2 rolled a " + playerRoll4);
}
}
Explanation / Answer
import java.util.Random ;
import java.util.* ;
public class PlayDieRoll
{
private int randvalues ;
public int getDieRolls()
{
return randvalues ;
}
public void setDieRolls
( int HIGHEST_DIE_RAND_VALUE , int LOWEST_DIE_RAND_VALUE )
{
int randvalues =( ( int ) ( Math.random () * 100 ) % 6 + 1 ) ;
}
}
-------------------------------------------------------------
public class twoDice2 {
public static void main ( String arguments[] )
{
int FirstDieRoll ;
int SecondDieRoll ;
PlayDieRoll Die =new PlayDieRoll() ;
Die.setDieRolls() ;
FirstDieRoll = Die.getDieRolls() ;
Die.setDieRolls() ;
SecondDieRoll = Die.getDieRolls() ;
System.out.println ( " The first die roll : " + FirstDieRoll ) ;
System.out.println ( " The second die roll : " + SecondDieRoll ) ;
if ( FirstDieRoll == SecondDieRoll )
{
System.out.println ( " The dices are equal " ) ;
}
else
if ( FirstDieRoll > SecondDieRoll )
{
System.out.println ( " Die 1 wins " ) ;
}
else
if ( FirstDieRoll < SecondDieRoll )
{
System.out.println ( " Die 2 wins " ) ;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.