In: Computer Science
Two people play the game of Count 21 by taking turns entering a
1, 2, or 3, which
is added to a running total. The player who adds the value that
makes the total
reach or exceed 21 loses the game. Create a game of Count 21 in
which a player
competes against the computer, and program a strategy that always
allows the
computer to win. On any turn, if the player enters a value other
than 1, 2, or 3,
force the player to reenter the value. Save the game as
Count21.java
Count21.java
import java.util.Random;
import java.util.Scanner;
public class Count21 {
   public static void main(String[] args) {
       // Scanner class object to accept
input from user
       Scanner input=new
Scanner(System.in);
       // Random class object to generate
random number
       Random random=new Random();
       System.out.println("*** COUNT 21
GAME ***");
       int yourTotal=0;
       int computerTotal=0;
       while(true) {
           int value;
           while(true)
{
          
    System.out.print("Enter a value (1/2/3):
");
          
    value=input.nextInt(); // accept value from
user
          
    // check entered value is correct or not
          
    if(value==1 || value==2 || value==3)
          
        break;
          
    System.out.println("You entered wrong value..try
again.!");
           }
           // add value
into user's total
          
yourTotal+=value;
           // generate
random number betweeen 1 to 3
           // and add it
into computer's total
          
computerTotal+=random.nextInt((3-1)+1)+1;
           // check user's
total
          
if(yourTotal>=21) {
          
    System.out.println("\n*** Computer won the game
***");
          
    break;
           }
           // check
computer's total
          
if(computerTotal>=21) {
          
    System.out.println("\n*** Congratulations...!!!
You won the game ***");
          
    break;
           }
       }
       System.out.println("*** THANK YOU
***");
       input.close(); // close Scanner
object
   }
}
Output
