In: Computer Science
We will simulate a dice game in which 2 dice are thrown.
Build your algorithm incrementally. First write a program that simulates a roll of two dice, then outputs if it is a simple win (7 or 11), or a simple loss (2 or 3 or 12), or something else.
//get a random number between 1 and 6, call it d1
//get a second random number between 1 and 6, call it d2.
//get the total & print it so we know what it was
//If the total is 7 or 11 print “Congratulations, you win”
//If the total is 2 or 3 or 12 print “You lose”
//If neither of these print “something else”
Sample output:
The total is 10
The new total is 8
The new total is 10
You win
Sample output:
The total is 9
The new total is 4
The new total is 8
The new total is 10
The new total is 5
The new total is 7
You lose
Sample output:
The total is 7
Congratulations, you win
Sample output:
The total is 12
You lose
Code language: Java use if-else statement
Since the question requires us to roll the dice and calculate total again and again, it is better if we create a function for the same. We are generating random numbers with the help of Math.random(). Everything that needs to be explained has been explained in the comments of the code. Further, the code output and code screenshot are available with this answer for your reference.
Java Program :
import java.util.*;
public class twoDice
{
public static void main(String[] args) {
// Get total
int total = getTotal();
System.out.println("The total is "
+ total);
// If total is 7 or 11, we
win
if(total == 7 || total ==
11){
System.out.println("Congratulations, you win");
}
// If total is 2,3 or 12, we
lose
else if(total == 2 || total == 3 ||
total == 12){
System.out.println("You
lose");
}
// Once a point is fixed, we
calculate newTotal till total gets equal to newTotal
else {
int newTotal=0;
while(newTotal!=total){
newTotal=getTotal();
System.out.println("The new total
is "+newTotal);
// If newTotal get equal to 7, we
lose
if(newTotal==7){
System.out.println("You
lose");
return;
}
}
System.out.println("Congratulations, you win");
}
}
// Function to calculate our total
public static int getTotal(){
int min = 1;
int max = 6;
int range = max-min+1;
int d1 = (int)(Math.random()*range)+min;
int d2 = (int)(Math.random()*range)+min;
int total = d1 + d2;
return total;
}
}
Code screenshot :
Output screenshots :
Solution ends.
Please comment and let me know if you have any further doubts. Please upvote this answer if you like it.
Thank you.
Have a good day.