Answer to Question #255665 in Java | JSP | JSF for Drishere

Question #255665

Write a program that rolls a pair of dice until the sum of the number rolled is a specific number. we also want to know the number of times the dice are rolled to get the desired number. the smallest number or each die is 1 and the larges number is 6. so the smallest sum of the numbers rolled is 2 and the largest sum of the numbers rolled is 12. we use the random number generator, to randomly generate a number between 1 to 6.

A. Create a statement that randomly generates a number between 1 to 6 and stores that number into die1, which becomes the number rollled by die1

B. Similarly, create a statement that randomly generates a number between 1 to 6 and that number into die2, which becomes the number rolled by die2.

C. Next, determine whether sum contains the desired sum, then we roll the dice again.

D. Create a method named rolldice that takes as a parameter the desired sum of the numbers to be rolled and returns the number of times the dice are rolled to roll the desired sum.


1
Expert's answer
2021-10-23T13:53:15-0400
import java.util.Random;
import java.util.Scanner;


public class App {
	/**
	 * The start point of the program
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner keyBoard = new Scanner(System.in);
		int desiredSum = 0;
		while (desiredSum < 2 || desiredSum > 12) {
			System.out.print("Enter the desired sum [2-12]: ");
			desiredSum = keyBoard.nextInt();
		}
		System.out.print("The number of times the dice are rolled to roll the desired sum: " + rolldice(desiredSum));
		keyBoard.close();


	}


	/**
	 * D. Create a method named rolldice that takes as a parameter the desired sum
	 * of the numbers to be rolled and returns the number of times the dice are
	 * rolled to roll the desired sum.
	 * 
	 * @param desiredSum
	 * @return
	 */
	private static int rolldice(int desiredSum) {
		int times = 1;
		Random rand = new Random();
		// A. Create a statement that randomly generates a number between 1 to 6 and
		// stores that number into die1, which becomes the number rollled by die1
		int die1 = rand.nextInt(6) + 1;
		// B. Similarly, create a statement that randomly generates a number between 1
		// to 6 and that number into die2, which becomes the number rolled by die2.
		int die2 = rand.nextInt(6) + 1;
		// C. Next, determine whether sum contains the desired sum, then we roll the
		// dice again.
		int sum = die1 + die2;
		while (sum != desiredSum) {
			die1 = rand.nextInt(6) + 1;
			die2 = rand.nextInt(6) + 1;
			sum = die1 + die2;
			times++;
		}
		return times;
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS