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
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