SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Program Logic And Indefinite Loops
Exercise:
Exercises
Question:7 | ISBN:9780136091813 | Edition: 2

Question

Write a method called diceSum that accepts a Scanner for the console as a parameter and prompts for a desired sum, then repeatedly simulates the rolling of 2 six-sided dice until their sum is the desired sum. Here is a sample dialogue with the user:
Desired dice sum: 9
4 and 3 = 7
3 and 5 = 8
5 and 6 = 11
5 and 6 = 11
1 and 5 = 6
6 and 3 = 9

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

package indefinite_loops;

import java.util.Random;
import java.util.Scanner;

public class Dice {

	public void diceSum() {
		// take scanner object
		Scanner scanner = new Scanner(System.in);
		System.out.print("Desired dice sum: ");
		int desiredSum = scanner.nextInt();
		
		// take Random object
		Random random = new Random();
		// generate two dice values in the range 1 to 6
		int dice1 = random.nextInt(6) + 1;
		int dice2 = random.nextInt(6) + 1;

		// runs till two dice values equals desired sum
		while (!((dice1 + dice2) == desiredSum)) {

			System.out.print(dice1 + " and " + dice2 + " = " + (dice1 + dice2)+ "\n");
			
			dice1 = random.nextInt(6) + 1;
			dice2 = random.nextInt(6) + 1;
		}
        // print last two dice values
		System.out.print(dice1 + " and " + dice2 + " = " + (dice1 + dice2));

		scanner.close();
	}

	public static void main(String[] args) {
		
		// call the method
		new Dice().diceSum();

	}

}
Output:

Desired dice sum: 9
5 and 2 = 7
6 and 6 = 12
5 and 5 = 10
1 and 6 = 7
1 and 5 = 6
3 and 5 = 8
5 and 1 = 6
5 and 6 = 11
3 and 6 = 9

 

0 0

Discussions

Post the discussion to improve the above solution.