In: Computer Science
----------USING JAVA-----------
Your objective is to beat the dealer's hand without going over 21.
Thank you!
Code is :
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Demo
{
public static void main (String[] args) throws java.lang.Exception
{
int card1,card2,card3=0,dcard,tcard;
System.out.println("Hello.. Welcome to 21");
//Random number object
Random rand = new Random();
Scanner sc= new Scanner(System.in);
//selecting card 1
//1 is added to the random number to make it between 1-10
card1 = rand.nextInt(10);
card1 += 1;
//selecting card 2
card2 = rand.nextInt(10);
card2 += 1;
System.out.println(" Your first card is "+card1);
System.out.println(" Your second card is "+card2);
//adding user cards
tcard=card1+card2;
while (tcard<21)
{
//prompting user for another card
System.out.println(" Would you like another card... y/n");
String cr = sc.nextLine();
if (cr.equals("y"))
{
//generating next card
card3 = rand.nextInt(10);
card3 += 1;
System.out.println(" Your next card is "+card3);
tcard += card3;
}
else
{
break;
}
}
//generating dealer hand
dcard = rand.nextInt(10);
dcard += 1;
dcard += 10;
System.out.println("Dealer hand: "+dcard+" Your hand: "+tcard);
//checking winner
if ((tcard>21)||(tcard==dcard)||(tcard<dcard))
System.out.println("Dealer wins");
else
System.out.println("You win");
}
}
Input: y y n
Output: