The real power in inheritance is in extending the capabilities of a class by cre
ID: 3545702 • Letter: T
Question
The real power in inheritance is in extending the capabilities of a class by creating another class that is a specialized
version of it. Consider the following program that simulates rolling a 6- sided die 50 times:
import java.util.Random;
// This program will simulate rolling a 6-sided die
// 50 times.
public class DiceGame
{
// roll die 50 times and display result
// takes in an already instantiated Random object.
public static void printDiceRolls(Random r)
{
int num;
int count = 0;
// roll 50 times (displaying each roll)
for (int i = 1; i < 50; i++)
{
num = r.nextInt(6) + 1;
System.out.print(num + " ");
if (num == 6)
count++;
}
// how many were 6s?
double percent = count/50.0*100;
System.out.println(" " + percent + "% were 6s");
}
public static void main(String [] args)
{
Random random = new Random();
printDiceRolls(random);
}
}
Create a class called LoadedDice( ) that represents a 6 sided die that is weighted towards the 6. On every roll, you
have a 50% of rolling a 6, and a 50% chance of rolling a 1, 2, 3, 4 or 5, with each number being equally likely.
LoadedDice will be derived from the Random class. Override the public int nextInt(int n)
method that is inherited from Random to return the largest number possible (n-1) 50% of the time, and all other
possible values are equally likely. Now, by making only one change to the program above, changing
Random random = new Random();
to
Random random = new LoadedDice();
The program should work as written, using a loaded die.
Submit only your LoadedDice() class.
Explanation / Answer
import java.util.Random;
public class LoadedDice extends Random
{
// override method
public int nextInt(int n)
{
if (nextBoolean())
return n-1;
return super.nextInt(n-1);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.