In: Computer Science
In Java please!!
Your objective is to beat the dealer's hand without going over 21. Cards dealt (randomly) are between 1 and 11. You receive 2 cards, are shown the total, and then are asked (in a loop) whether you want another card. You can request as many cards as you like, one at a time, but don't go over 21. (If you go over 21 it should not allow you any more cards and you lose) Determine the dealer's hand by generating a random number between 1 and 11 and adding 10 to it. Compare your hand with the dealer's hand and indicate who wins (dealer wins a draw)
import java.util.*;
public class BeatDealer {
        public static void main(String[] args) {
                Scanner scanner = new Scanner(System.in);
                String answer = "";
                int you = 0;
                System.out.println("Your Score " + you);
                int dealer = getRandomNumber(1, 11) + 10;
                while (true) {
                        System.out.print("Do you want another card? (y / n) ");
                        answer = scanner.nextLine();
                        
                        if (answer.equals("y")) {
                                int num = getRandomNumber(1, 11);
                                you+=num;
                                if (you <= 21) {     
                                        System.out.println("Your Score " + you);
                                } else {
                                        System.out.println("Your Score " + you);
                                        System.out.println("Your Score reached more than 21");
                                        System.out.println("Sorry! You lost the game");
                                        break;
                                }
                        } else {
                                if (you > dealer) {
                                        System.out.println("You won the game, "+ "You - " +you+ " Dealer - "+dealer);
                                } else if(you == dealer) {
                                        System.out.println("Draw, "+ "You - " +you+ " Dealer - "+dealer);
                                } else {
                                        System.out.println("Dealer won the game, "+ "You - " +you+ " Dealer - "+dealer);
                                }
                                break;
                        }
                }
        }
        static int getRandomNumber(int min, int max) {  
                return (int) ((Math.random() * (max - min)) + min);
        }
}