In: Computer Science
My code:
import java.util.Random;
import java.util.Scanner;
public class RollDice {
public static void main(String[] args) {
int N;
Scanner keybd = new Scanner(System.in);
int[] counts = new int[12];
System.out.print("Enter the number of trials: ");
N = keybd.nextInt();
Random die1 = new Random();
Random die2 = new Random();
int value1, value2, sum;
for(int i = 1; i <= N; i++) {
value1 = die1.nextInt(6) + 1;
value2 = die2.nextInt(6) + 1;
sum = value1 + value2;
counts[sum-1]++;
}
System.out.printf("%10s %10s %10s\n", "Outcome", "Number",
"Percent");
for(int i = 2; i <= 12; i++) {
double perc = counts[i-1] * 100.0 / N;
System.out.printf("%10d %10d %10.1f%%\n", i, counts[i-1],
perc);
}
}
}
Prompts:
- After running, have your code ask the user if they wish to run the simulation again. If they answer "yes", start over at the beginning. If they answer "no", terminate the program.
- In addition to asking for the number of trials, prompt the user to enter the number of dice to be rolled for the trials (so each trial could roll 3 dice, with sums of 3 to 18, or 10 dice, with sums of 10 to 60).
- In addition to asking for the number of trials, prompt the user to enter the number of sides that the dice have.
If you have any problem with the code feel free to comment.
Program
import java.util.Random;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
int N;
Scanner keybd = new
Scanner(System.in);
String choice;//for taking user
choice
while (true) {//infinite loop
//taking all
inputs
System.out.print("Enter the number of trials: ");
N =
keybd.nextInt();
keybd.nextLine();
System.out.print("Enter the number of Dice: ");
int numDice =
keybd.nextInt();
keybd.nextLine();
System.out.print("Enter the number of sides: ");
int sides =
keybd.nextInt();
keybd.nextLine();
int len = sides
* numDice;//calculating length
int[] counts =
new int[len];
Random die1 =
new Random();
int value1,
sum;
for (int i = 1;
i <= N; i++) {
value1 = die1.nextInt(sides) + 1;
sum = value1 * numDice;//finding value of
dice
counts[sum - 1]++;
}
System.out.printf("%10s %10s %10s\n", "Outcome", "Number",
"Percent");
for (int i =
numDice; i <= len; i++) {//loop the output
double perc = counts[i - 1] * 100.0 / N;
System.out.printf("%10d %10d %10.1f%%\n", i,
counts[i - 1], perc);
}
//asking for
user choice to continue
System.out.print("\nDo you wish to continue?(Y/N) ");
choice =
keybd.nextLine();
if(choice.equalsIgnoreCase("N"))
break;//loop end statement
}
keybd.close();
}
}
Output