In: Computer Science
Roll dice java program
The program simulates a dice roll by generating a random integer between 1 and 6
Hope this will help you. If you have any doubt please let me know.
If you want any modification in the program please let me know. I will do it, because there was no other instruction provided in the program.
Please go through all the notes.
Notes: There were no other instructions or restrictions provided in the problem statement except generate Random number.
There are 2 ways we can generate a random number 1) using Math class and 2) using a Random Class.
Over here not specified which one to use hence both are provided in code. Method using a math class is commented if you want to use this uncomments that line.
All line of code is commented.
A screenshot of the output is also attached.
If you want any modification in the program please let me know. I will do it.
---------------------------------------Coding--------------------------------------
import java.util.Scanner;/*to read user input*/
import java.util.Random; /*for random number*/
public class RollDiceSimulation{ /*class */
public static void main(String[] args){ /*main*/
int n; /*int n to print a value
*/
Scanner sc= new Scanner(System.in);
/*scanner class to read an input for user */
Random rand = new Random();
/*random class object*/
char ch; /*to read a character*/
do {
System.out.print("Face values of the dice is: ");
/*print message*/
n=rand.nextInt(6)+1;/*random number generator between
1 and 6 nextInt(6) generate random number between 0 and 5 and
adding 1 into it makes between 1 to 6*/
//n=(int) (Math.random()*6+1);/*2nd method to generate
a random number */
System.out.println(n); /*printing a dice value*/
System.out.print("Do you want to countinue? (Press Y
for yes, or any other character for no.)"); /*asking for other
input*/
ch=sc.next().charAt(0);/*scanning a first char*/
}while(ch=='Y'||ch=='y');/*if ch==y again roll dice*/
System.out.println("-----SIMULATION
ENDS---------");/*printing a msg*/
}
}
-----------------------------------Screen-shot--------------------------------------