Write a game program that prints a chart to the screen showing the randomness of
ID: 3641918 • Letter: W
Question
Write a game program that prints a chart to the screen showing the randomness of a dice. The game should first prompt the client for a number of die throws that he would like. The game then throws the die that many times. The game then prints a chart showing a line of asterisks for each die number, indicating the number of times the die landed with that face number on top. Allow the client to repeat the game as many times as she wishes. Use at least three methods: One for input, one for processing, and one for output. A sample output would look like this:This game prompts the user for a number of die throws.
The game then displays a chart indicating the number
Of times the die landed with that face number on top.
Please enter the number of times that
You would like to throw the dice: 100
The chart showing 100 throws of the dice:
1 ******************
2 ****************
3 **************
4 *******************
5 **************
6 *******************
Would you like to play the game again?
Please enter (yes/no) no
Explanation / Answer
import java.util.Scanner;
public class DiceThrowingChart {
public static void main(String[] args) {
final int DICE_FACE_COUNT = 6;
Scanner keyboard = new Scanner (System.in);
int numberOfTimes;
int [] diceValues = new int[DICE_FACE_COUNT];
String response = "yes";
while (response.compareTo("yes") == 0) {
//Init
for (int i = 0; i < diceValues.length; i++) {
diceValues[i] = 0;
}
//Ask for number of dice throws
System.out.println("Please enter the number of times that");
System.out.print("you would like to throw the dice: ");
numberOfTimes = keyboard.nextInt();
System.out.println("The chart showing " + numberOfTimes + " throws of the dice:");
//Throw dice and count
while(numberOfTimes > 0) {
int result = (int)(DICE_FACE_COUNT * Math.random()); //0-5 for easier counting
diceValues[result]++;
numberOfTimes--;
}
//Print the chart
for (int i = 0; i < diceValues.length; i++) {
System.out.print(i + 1 + " ");
for (int astr = 0; astr < diceValues[i]; astr++) {
System.out.print("*");
}
System.out.println();
}
//Ask for another game
System.out.println(" Would you like to play the game again?");
System.out.print("Please enter (yes/no) ");
response = keyboard.next();
System.out.println();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.