I am trying to create a simple Blackjack game in Java. I have a menu with possible integer options from 1-4. If the user inputs an integer greater than 4, my IF statement needs to print "invalid integer" and then restart the game. If the user inputs a negative value, my ELSE-IF statement needs to do the same thing.
However, the statements will only work once, so I can't get "invalid integer" to print if I input values below 0 and values greater than 4 multiple times/back-to-back.
Code:
System.out.print("1. Get another card\n" +
"2. Hold hand\n" +
"3. Print statistics\n" +
"4. Exit\n" + "Choose an option: ");
userOpt = scnr.nextInt();
if (userOpt > 0) {
switch (userOpt) {
case 1:
if (playerHand == 21) {
System.out.println("BLACKJACK! You win!");
playerWins++;
gameCounter++;
System.out.println("START GAME #" + gameCounter);
playerHand = 0;
} else if (playerHand > 21) {
System.out.println("You exceeded 21! You lose!");
dealerWins++;
gameCounter++;
System.out.println("START GAME #" + gameCounter);
playerHand = 0;
}
break;
case 2:
dealer = generatedNumber.nextInt(11) + 16;
if (dealer > 21) {
System.out.println("You win!");
playerWins++;
gameCounter++;
System.out.println("START GAME #" + gameCounter);
playerHand = 0;
} else if (dealer == playerHand) {
System.out.println("It's a tie! No one wins!");
tieGames++;
gameCounter++;
System.out.println("START GAME #" + gameCounter);
playerHand = 0;
} else {
System.out.println("Dealer wins!");
dealerWins++;
gameCounter++;
System.out.println("START GAME #" + gameCounter);
playerHand = 0;
}
break;
case 3:
System.out.println("Number of Player wins: " + playerWins);
System.out.println("Number of Dealer wins: " + dealerWins);
System.out.println("Number of tie games: " + tieGames);
System.out.println("Total # of games played is: " + gameCounter);
double playerwinsNew = playerWins;
percentage = (((playerwinsNew * 100)) / (gameCounter));
System.out.println("Percentage of Player wins: " + percentage + "%");
case 4:
break;
default:
System.out.println("Invalid input!\n" + "Please enter an integer value between 1 and 4.");
System.out.print("1. Get another card\n" +
"2. Hold hand\n" +
"3. Print statistics\n" +
"4. Exit\n" + "Choose an option: ");
userOpt = scnr.nextInt();
continue;
}
} else if (userOpt < 0) {
System.out.println("Invalid input!\n" + "Please enter an integer value between 1 and 4.");
System.out.print("1. Get another card\n" +
"2. Hold hand\n" +
"3. Print statistics\n" +
"4. Exit\n" + "Choose an option: ");
userOpt = scnr.nextInt();
continue;
}
Any help is appreciated.
Aucun commentaire:
Enregistrer un commentaire