a. In chapter 4 you created a Die class that you can use to instantiate objects
ID: 3668991 • Letter: A
Question
a. In chapter 4 you created a Die class that you can use to instantiate objects that hold one of six randomly selected values. Modify this class so its value field is protected instead of private. This will allow a child class to access the value. Save the file as Die.java.
b. Create a LoadedDie class that can be used to give a player a slight advantage over the computer. A LoadedDie never rolls a 1; it only rolls values 2 through 6. Save the file as LoadedDie.java
c. Create a program that rolls two Die objects against each other 1,000 times and counts the number of times the first Die has a higher value than the other Die. then roll a Die object against LoadedDie object 1,000 times, and count the number of times the Die wins. Display the results. Save the application as TestLoadedDie.java.
Explanation / Answer
a)
class Die {
protected int HIGHEST_DIE_VALUE = 6;
protected int LOWEST_DIE_VALUE = 1;
protected int randomValue;
public int getRandomValue() {
randomValue = ((int) (Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
return randomValue;
}
public void setRandomValue(int value) {
randomValue = value;
}
}
b)
class LoadedDie {
protected int HIGHEST_DIE_VALUE = 6;
protected int LOWEST_DIE_VALUE = 2;
protected int randomValue;
public int getRandomValue() {
randomValue = ((int) (Math.random() * 100) % HIGHEST_DIE_VALUE + LOWEST_DIE_VALUE);
return randomValue;
}
public void setRandomValue(int value) {
randomValue = value;
}
}
c)
class TestTwoDie{
public static void main(String[] args) {
Die die1 = new Die();
Die die2 = new Die();
int count = 0;
for(int i=0; i<1000;i++){
if(die1.getRandomValue() > die2.getRandomValue())
count++;
}
System.out.println("Die1 has "+count+" number of times greater value than other Die.");
}
}
class TestLoadedDie{
public static void main(String[] args) {
Die die1 = new Die();
LoadedDie die2 = new LoadedDie();
int count = 0;
for(int i=0; i<1000;i++){
if(die1.getRandomValue() > die2.getRandomValue())
count++;
}
System.out.println("Die1 has "+count+" number of times greater value than LoadedDie.");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.