I'm trying to create a blackjack game, where the player starts off with 2 cards, and then asked if he/she would like to have another card (user input: yes or no), if yes, another card is added to the total. if no, the game just terminates.
Here is a sample output I'm trying to get:
And this is what I have so far (It's probably wrong in terms of the placement):
import java.util.Scanner;
public class BlackJackGame {
public static void main(String[] args) {
int randomnum1 = (int) (1 + Math.random() * 10);
int randomnum2 = (int) (1 + Math.random() * 10);
int randomnum3 = (int) (1 + Math.random() * 10);
int total;
char anotherCard = 'y';
Scanner input = new Scanner(System.in);
System.out.println("First cards: " + randomnum1 + ", " + randomnum2);
total = randomnum1 + randomnum2;
System.out.println("Total: " + total);
while (anotherCard != 'n')
{
System.out.print("Card: " + randomnum3);
System.out.print("Do you want another card? (y/n): ");
anotherCard = input.next().charAt(0);
}
}
}
Tips and reworking the source code will be highly appreciated.
Here are the tips you requested:
int sum = randomnum1 + randomnum2;
and keep adding the next card to it inside the loop:sum += randomnum3;
randomnum3
inside the while loop. This way, you will get a different card every time. Basically, you have to call the random function every time you generate a card, not just once. Otherwise the value ofrandomnum3
will be unchanged and you will get the same card over and over.if
and possiblybreak
within the loop, once you have added the current card to the sum:if(sum > 21) { break; }
anotherCard
to'n'
instead of using abreak
Here are a few simple improvements for you to look over. I'll leave it like this as part of the joy of learning to program is in the discovery. As a next step I'd suggest generating a dealers hand and then seeing if the player can beat it. Good luck!
As Far as card games go, there are 52 cards in a deck, and I'm assuming there's one deck.
If you want it to be a fair game, then you have to keep that in mind.
But if you just want output to look correct, you just have to avoid getting more than 4 aces, 2's, 3's, and 4's.
One way to achieve this would be to make an int array of size 52 with 4 of each card. I suppose Ace would be 1 and 10,J,Q,K would be 10, so there would be 16 10's.
Get a random number between 0 and 51 to get the index of the array you want to use. Once you use that index, set the value of that array = -1, and always check for -1 before using that index, and if it is -1, get another random value.
something like that.. I just did that quickly, hopefully you get the idea.