In: Computer Science
Java Programming Activity Description: This lab requires you to simulate the rolling of two dice. Two dice consisting of 6 sides are rolled. Write a program that simulates this. The user will be asked if he/she wishes to continue the roll of dice. If the answer is, “Y” or “y”, then your application will continue to roll the two dice. Each roll of the dice must occur 6 times, each time the user agrees to continue (see sample output). Use a for loop in order to keep track of the number of times the dice are rolled.
Explanation:
Here is the code which has the Scanner object and the Random object.
A while loop is there, which keeps running until the user presses y or Y every time to roll the dice again.
Everytime, the rolls are printed on both the die.
Code:
import java.util.Scanner;
import java.util.Random;
public class Main
{
public static void main(String[] args) {
Scanner sc = new
Scanner(System.in);
Random r = new Random();
int first, second;
while(true)
{
first = r.nextInt(6) + 1;
second = r.nextInt(6) + 1;
System.out.println("First Dice:
"+first+" Second Dice: "+second);
System.out.print("Do you want to
roll again? ");
String answer =
sc.nextLine();
if(!answer.equals("y") &&
!answer.equals("Y"))
break;
}
}
}
Output:
PLEASE UPVOTE IF YOU FOUND THIS HELPFUL!
PLEASE COMMENT IF YOU NEED ANY HELP!