GAME OF TWENTY-ONE Write a Java program that lets the user play against the comp
ID: 665516 • Letter: G
Question
GAME OF TWENTY-ONE
Write a Java program that lets the user play against the computer in a variation of the popular blackjack card game. In this variation, two six-sided dice are used instead of cards. The dice are rolled, and the player tries to beat the computer's hidden total without going over 21.
- Each round of the game is performed as an iteration of a loop that repeats as long as the player agrees to roll the dice, and the player's total does not exceed 21.
- At the beginning of each round, the program will ask the user whether or not he or she wants to roll the dice to accumulate points.
- During each round, the program simulates the rolling of two six-sided dice. It rolls the dice first for the computer, then asks the user whether he or she wants to roll.
- The loop keeps a running total of both the computer's and the user's points.
- The computer's total should remain hidden until the loop has finished.
- After the loop has finished, the computer's total is revealed, and the player with the most points, without going over 21, wins.
Explanation / Answer
import java.util.Scanner;
import java.util.Random;
public class GameTwentyOne {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
Random randomGenerator = new Random();
int computerScore=0,humanScore=0;
while(true)
{
int total,diceRoll1,diceRoll2;
diceRoll1= randomGenerator.nextInt(6)+1;
diceRoll2= randomGenerator.nextInt(6)+1;
total=diceRoll1+diceRoll2+computerScore;
if(total>21)
break;
System.out.println("Do you want to roll the dice to accumulate points?(y/n)");
char te=sc.next().charAt(0);
if(te=='n')
break;
computerScore=total;
diceRoll1= randomGenerator.nextInt(6)+1;
diceRoll2= randomGenerator.nextInt(6)+1;
total=diceRoll1+diceRoll2+humanScore;
if(total>21)
break;
humanScore=total;
}
System.out.println("The game is over.");
if(computerScore>humanScore)
{
System.out.println("Sorry you lost. Computer Score: "+computerScore+" Your Score: "+humanScore);
}
else if (computerScore==humanScore)
{
System.out.println("The game was a tie. Computer Score: "+computerScore+" Your Score: "+humanScore);
}
else
{
System.out.println("Hurray you won. Computer Score: "+computerScore+" Your Score: "+humanScore);
}
double x, y, z;
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.