I'm programming Blackjack and all is well, except after I type 'y' to hit again, the program terminates even though total is still less then 21. So my while statement is doing nothing?

package com.github.geodox.blackjack;

import java.util.Random;
import java.util.Scanner;

public class Blackjack
{
    private static int total = 0;
    private static Random rand = new Random();
    private static Scanner scan = new Scanner(System.in);

    public static void main(String[] args)
    {
        int card1 = rand.nextInt(11)+1;
        System.out.println(card1);
        int card2 = rand.nextInt(11)+1;
        System.out.println(card2);

        if(card1 == 11 & card2 == 11)
            total = 12;
        else
            total = card1 + card2;

        System.out.println(total);

        while(total < 21)
        {
            if(total < 21)
            {
                System.out.println("Hit? y/n: ");
                String hit = scan.nextLine();
                if(hit.equals("y"))
                {
                    total += rand.nextInt(11)+1;
                    hit = null;
                }
                else if(hit.equals("n"))
                {
                    System.out.println("Your total is: " + total);
                    break;
                }
                else
                {
                    System.out.println("Invalid Response");
                    System.out.println("Your total was: " + total);
                    break;
                }
            }
            else
                System.out.println("BUST! Your total is: " + total);
            break;
        }
        scan.close();
    }
}

not so sure. can you add a print statement of total after this line:
total += rand.nextInt(11)+1;
it's better to declare hit outside the while though.

You have a break; as the last statement in your loop, so it will always exit the loop at the end of its first pass. Maybe you intended that to be inside the else block?
Also: the if test on line 28 is redundant.

commented: I missed that one ... +0

DoogleDude, is there a specific reason you down-voted my reply?
if you re-read it, and compare it to your original question, it is a valid point.
I've run your code myself, with that added print statement, and not a single time did I encounter this:

the program terminates even though total is still less then 21.

the value of total was well over 21, you just didn't print the value, so you didn't know it was over 21.

Sorry about that, finally read it correctly. I thought you meant there was something wrong with doing a += operator directly to total.
Yes, you're right, it is a good thing to declare it outside.
Thanks for the help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.