Write a program in Java that simulates rolling two dice using the following step
ID: 3629157 • Letter: W
Question
Write a program in Java that simulates rolling two dice using the following steps:1. Prompt the use for the number of sides for two dice.
2. "Roll" the dice three times by generating a random number between 1 (inclusive) and the number of sides (inclusive).
3. Keep track of the sum of the rolls for each dice and output the sum and average for each dice.
What a sample output should say from program:(Will not say this exactly, its random)
How many sides does die 1 have? 6
How many sides does die 2 have? 20
Die 1 first roll = 5.
Die 2 first roll = 14.
Die 1 second roll = 3
Die 2 second roll= 20.
Die 1 third roll = 3.
Die 2 third roll = 9.
Die 1 rolled a total of 9 and rolled 3 on average.
Die 2 rolled a total of 43 and rolled 14.333 on average.
Explanation / Answer
import java.util.*;
class test
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String[] rose={"first" , "second" , "third"};
System.out.println("How many sides does die 1 have? ");
int die1 = sc.nextInt();
System.out.println("How many sides does die 2 have? ");
int die2 = sc.nextInt();
int sum1=0;
int sum2=0;
for(int i=0; i<3; i++)
{
int value1 = (int)(Math.random() * die1) + 1;
System.out.println("die 1 " + rose[i] + " roll " + value1);
sum1 = sum1 + value1;
int value2 = (int)(Math.random() * die2) + 1;
System.out.println("die 2 " + rose[i] + " roll " + value2);
sum2 = sum2 + value2;
}
double avg = sum1/3.0;
double avg1 = sum2/3.0;
System.out.println("Die 1 rolled a total of " + sum1 +" and rolled " + avg +" on average.");
System.out.println("Die 2 rolled a total of " + sum2+" and rolled " + avg1 +" on average.");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.