I have a problem with my dealerhand method in my blackjack game.
I have a method to produce a random card from the class deck.
The cards have assigned values to them and so forth.
however the problem lies in the code where i want the dealer to draw a new card, and add the value to the existing total hand value. the code is a following.
//Basics for the values of dealers cards
int dealerHandValue = 0;
int tempDealerHandValue = 0;
int totalDealerHandValue= 0;
//Dealers first card
randomGenNum = (int)((range * Math.random()) + 1)*2;
dealerHandValue = arrayCardRank[randomGenNum];
CardSuit = arrayCardSuit[randomGenNum];
System.out.println("Dealer First Card Shows : " + (CardSuit));
tempDealerHandValue = dealerHandValue;
//Code executed when player stops drawing and stands.
while (totalDealerHandValue < 18 && totalDealerHandValue <21)
{
randomGenNum = (int)((range * Math.random()) + 1)*2;
dealerHandValue = arrayCardRank[randomGenNum];
CardSuit = arrayCardSuit[randomGenNum];
System.out.println("Dealer next Card Shows : " + (CardSuit));
tempDealerHandValue = dealerHandValue;
totalDealerHandValue = (tempDealerHandValue) + (dealerHandValue);
System.out.println("Dealer total hand value is " + (totalDealerHandValue));
}
{
System.out.println("Dealer stopped drawing");
if (totalDealerHandValue >= totalUserHandValue)
{
System.out.println("Dealer wins");
return;
}
else
System.out.println("Congratulations! You Win!");
return;
}
This method will just add the new cards value to itself, on and on until the while statement ends.
i have gone blind on the problem, and i know it is easily fixed.
can anyone help me towards what i am missing?
you're never incrementing totalDealerHandValue, just overwriting the value over and over again.
Replace these two lines:
tempDealerHandValue = dealerHandValue;
totalDealerHandValue = (tempDealerHandValue) + (dealerHandValue);
with
totalDealerHandValue += dealerHandValue;
Related
I am trying to write code for a game that has a player and a computer roll dice until one, or both, reach 250( its possible for them to tie). The player and the computer can choose from 1 of 3 die choices. One - 24 sided tie, two - 10 sided die, or three - 6 sided die. There is a bonus for the 10 and 6 sided die if the die are all the same. There are 2 "lakes" where if the player lands in them the player has to go back to the lower number right before the beginning of the lake, there is also a muddy swamp where every move the player makes while in the swamp is cut in half. For every 10 spots (10, 20, 30, 40 ETC.) the player randomly draws a card. There are 11 different cards the player can randomly get:
1-4: player moves ahead a random amount from 1-6
5: player moves ahead a random amount from 4-11 (random 8 + 4)
6: player moves to where the other player is (see below)
7: player moves back to the beginning (moves to location 0)
8-9: player moves back a random amount from 1-6
10-11: player moves back a random amount from 4-11
I have a few problems. My first problem is that the die rolls do not change after every turn, they will remain the same. So if I choose 3 die I might get 3 random numbers, if I choose those die again I will get those same 3 numbers.
I also cannot seem to get the players die count to correctly update. If the player rolls 18 total points and the next turn he rolls 14 the count will go from 18 to 14.
My third problem is it seems like no matter what I do the print statement for the lakes,muddy patch and the winner announcement always print. I have tried a few different things and nothing seems to work.
I am new at code writing ( this is my 4th program written) and do not have extensive knowledge to know what is wrong. The code does not have to be expertly done, I just would like it to work properly. Any and all help is greatly appreciated.
/*This program will create a "Board" game. Each player can choose
from several different types of die. The computer and user will take
turns "rolling" a dice. There are several obstacles that can send one
of the players back. The goal is to get above 250*/
import java.util.*;
public class Project4 {
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
//assigning variables
int p1, p2;
p1=p2=0;
int spacesmoved = 0;
//Setting up the randomization of the 24 sided die
int minimum1 = 1;
int maximum1 = 24;
Random rn1 = new Random();
int range1 = maximum1 - minimum1 + 1;
int die1 = rn1.nextInt(range1) + minimum1;
//Setting up the randomization of the 10 sided die
int minimum2 = 1;
int maximum2 = 10;
Random rn2 = new Random();
int range2 = maximum2 - minimum2+ 1;
int die2 = rn2.nextInt(range2) + minimum2;
int die22 = rn2.nextInt(range2) + minimum2;
int die222 = rn2.nextInt(range2) + minimum2;
//Setting up the randomization of the 6 sided die
int minimum3 = 1;
int maximum3 = 10;
Random rn3 = new Random();
int range3 = maximum3 - minimum3+ 1;
int die3 = rn3.nextInt(range3) + minimum3;
int die33 = rn3.nextInt(range3) + minimum3;
int die333 = rn3.nextInt(range3) + minimum3;
//Setting a loop for the players to take turns until one, or both, reach > 250
while (p1 <= 250 && p2 <= 250) {
{System.out.println(" Current positions. Player: " + p1 + " Computer: " + p2);
System.out.println("Which die would you like to roll? die1(1) = one 24-sided die, die2(2) = two 10-sided dice, die3(3) = three 6-sided dice: ");
String diechoice = in.nextLine().toLowerCase();
//Getting the die roll if the player chooses the 24 sided die
if (diechoice.equals ("1")) {
spacesmoved = (die1);
System.out.println("Player rolled a " + die1);
System.out.println("Player moves forward " + die1 +" spaces");
p1+=spacesmoved;
}
//Getting the die roll if the player chooses the two 10 sided die
if (diechoice.equals ("2")) { spacesmoved = (die2 + die22);
System.out.println("First die is " + die2);//TESTTTT
System.out.println("Second die is a " + die22);//TEST
System.out.println(die2 + die22);//TESTTTTtttt
if (die2 == die22); {
spacesmoved = (die2 + die22 + die222);
System.out.println("Player rolled doubles, player gets to roll a 3rd 10 sided die");
System.out.println("Players 3rd dice roll is " + die222);
System.out.println("Player moves forward a total of " + spacesmoved + " spots");
p1 += spacesmoved;
}
// player1spot = (currentspot + spacesmoved);
}
//Getting the die roll if the player chooses three 6 sided die
if (diechoice.equals("3")) { spacesmoved = (die3 + die33 + die333);
System.out.println("die 1 is " + die3);
System.out.println("die 2 is " + die33);
System.out.println("die 3 is " + die333);
System.out.println("Player 1 moves forward a total of " + spacesmoved + " spots");
{ if (die3 == die33)
if (die33 == die333)
spacesmoved = ( spacesmoved * 2);
p1 += spacesmoved;
}}
/*Setting up the lakes and muddy patch. If the player lands in a lake he goes back
to the lower edge of the lake. If in the mud his moves are cut in half ONLY while in the mud */
{if (spacesmoved >= (83) || spacesmoved <= (89)); spacesmoved = (82);
System.out.println("Player landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (152) || spacesmoved <= (155)); spacesmoved = (151);
System.out.println("Player landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (201) || spacesmoved <= (233)); spacesmoved = (spacesmoved / 2);
System.out.println("Player landed in mud, players turns are cut in half until player gets out");
}
//Setting up the random cards if the player lands on a 10
if (p1 % 10==0);
{ int minimum4 = 0;
int maximum4 = 11;
Random rn4 = new Random();
int range4 = maximum4 - minimum4 + 1;
int card = rn4.nextInt(range4) + minimum4;
//if player gets a card that moves them ahead a random number between 1-6
if (card >=4);
int minimum = 0;
int maximum = 6;
Random rn = new Random();
int range = maximum - minimum + 1;
int cardmove = rn.nextInt(range) + minimum;
p1 = cardmove;
//if player gets a card that moves them ahead a random number between 4-11
if (card == 5);
int minimum5 = 4;
int maximum5 = 11;
Random rn5 = new Random();
int range5 = maximum5 - minimum5 + 1;
int cardmove5 = rn5.nextInt(range5) + minimum5;
p1 = cardmove5;
//if player gets a card that moves them to the spot of the other player
if (card == 6);
p2 = p1;
//if player gets a card that moves them back to 0 (moves location to 0)
if (card ==7);
p1 = 0;
//if player gets a card that moves them back between 1-6 spaces
if (card == (8) || card == 9);
int minimum6 = 1;
int maximum6 = 6;
Random rn6 = new Random();
int range6 = maximum6 - minimum6 + 1;
int cardmove6 = rn6.nextInt(range6) + minimum6;
//if player gets a card that moves them back between 4-11 spaces
if (card == (10) || card == 11);
int minimum7 = 4;
int maximum7 = 11;
Random rn7 = new Random();
int range7 = maximum7 - minimum7 + 1;
int cardmove7 = rn7.nextInt(range7) + minimum7;
}
//Setting up the computers turn
System.out.println("Computers turn");
{
int minimum = 0;
int maximum = 2;
Random rn = new Random();
int range = maximum - minimum + 1;
int computersturn = rn.nextInt(range) + minimum;
//If computer randomly chooses a 24 sided die
spacesmoved = (die1);
System.out.println("Computer rolled a " + die1);
System.out.println("Computer moved " + die1 +" spaces");
p2+=spacesmoved;
}
//If the computer randomly chooses the two 10 sided die
if (diechoice.equals ("die2")) { spacesmoved = (die2 + die22);
System.out.println("First die is " + die2);//TESTTTT
System.out.println("Second die is a " + die22);//TEST
System.out.println(die2 + die22);//TESTTTTtttt
if (die2 == die22); {
spacesmoved = (die2 + die22 + die222);
System.out.println("Computer rolled doubles, player gets to roll a 3rd 10 sided die");
System.out.println("Computer 3rd dice roll is " + die222);
System.out.println("Computer moves a total of " + spacesmoved + " spots");
p2 += spacesmoved;
}
}
//If the computer randomly chooses three 6 sided die
if (diechoice.equals("die3")) { spacesmoved = (die3 + die33 + die333);
System.out.println("die 1 is " + die3);
System.out.println("die 2 is " + die33);
System.out.println("die 3 is " + die333);
System.out.println("Computer 1 moves a total of " + spacesmoved + " spots");
{ if (die3 == die33)
if (die33 == die333)
spacesmoved = ( spacesmoved * 2);
p2 += spacesmoved;
}
//Setting the lakes and mud for the computer
if (spacesmoved >= (83) || spacesmoved <= (89)); spacesmoved = (82);
System.out.println("Computer landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (152) || spacesmoved <= (155)); spacesmoved = (151);
System.out.println("Computer landed in a lake, player goes back to space " + spacesmoved);
if (spacesmoved >= (201) || spacesmoved <= (233)); spacesmoved = (spacesmoved / 2);
System.out.println("Computer landed in mud, players turns are cut in half until player gets out");
//Setting up the cards for the computer
if (p1 % 10==0);
{ int minimum4 = 0;
int maximum4 = 11;
Random rn4 = new Random();
int range4 = maximum4 - minimum4 + 1;
int card = rn4.nextInt(range4) + minimum4;
//if computer gets a card that moves them ahead a random number between 1-6
if (card >=4);
int minimum = 0;
int maximum = 6;
Random rn = new Random();
int range = maximum - minimum + 1;
int cardmove = rn.nextInt(range) + minimum;
//if computer gets a card that moves them ahead a random number between 4-11
if (card == 5);
int minimum5 = 4;
int maximum5 = 11;
Random rn5 = new Random();
int range5 = maximum5 - minimum5 + 1;
int cardmove5 = rn5.nextInt(range5) + minimum5;
//if computer gets a card that moves them to the spot of the other player
if (card == 6);
p1 = p2;
//if computer gets a card that moves them back to 0 (moves location to 0)
if (card ==7);
p1 = 0;
//if computer gets a card that moves them back between 1-6 spaces
if (card == (8) || card == 9);
int minimum6 = 1;
int maximum6 = 6;
Random rn6 = new Random();
int range6 = maximum6 - minimum6 + 1;
int cardmove6 = rn6.nextInt(range6) + minimum6;
//if computer gets a card that moves them back between 4-11 spaces
if (card == (10) || card == 11);
int minimum7 = 4;
int maximum7 = 11;
Random rn7 = new Random();
int range7 = maximum7 - minimum7 + 1;
int cardmove7 = rn7.nextInt(range7) + minimum7;
}
}
//Writing a final statment showing the winner, or if both tied.
{ if (p1 > p2);
System.out.println("Player 1 wins! Good job!");
if (p2 >p1);
System.out.println("Computer wins! Better luck next time!");
if (p2 == p1);
System.out.println("The game ends in a tie!");
}
}
}
}
}
Here are the things I noticed in relation to the three problems you mentioned:
Problem number 1:
You are setting the values of the dice at the very beginning of code execution. From that point on, you aren't changing them at all. That is the cause of the problem of always rolling the same numbers every turn. You might be thinking that every time you use die1 or any of the other die variables, that it is re-executing the code at the top of your file, but it doesn't.
The code at the top of your file is executed only once and then the value stored in that variable is used for the rest of the program execution. Until you change it. So you would want something more like this:
//Getting the die roll if the player chooses the 24 sided die
if (diechoice.equals ("1")) {
die1 = rn1.nextInt(range1) + minimum1;
System.out.println("Player rolled a " + die1);
System.out.println("Player moves forward " + die1 +" spaces");
p1+=die1;
}
You would also need to change that in the other cases where the die is rolled.
Another benefit to doing it this way is that you really only need one random number generator. You don't actually need one for each die. You can use the same one for all die rolls.
Problem number 2:
I'm not sure exactly what is going wrong with die rolls, if there really is something going wrong there, but I did notice a few places where you'll want to change what is done to p1 and p2:
When the player gets a card that moves them ahead, you'll want to use += instead of =. i.e. p1 += cardmove5 instead of p1 = cardmove5
When the player gets a card that moves them back, it looks like you forgot to add the p1 -= cardmove statements.
Also, make sure you have p1 and p2 in the right places. For example, I'm thinking that on the computer's turn, if they get the card to move them to the other player's spot, you meant to do p2 = p1, but instead you have p1 = p2. Same with the computer going back to 0. You have p1 = 0, but it seems like you would want p2 = 0. So just be careful about that. (Also be careful about copy paste. I'm guessing that's why that happened)
Problem number 3:
This problem looks like it's caused by the fact that you are using the || operator where you should be using &&. When you use ||, you are effectively saying "or". So this first statement
if (spacesmoved >= (83) || spacesmoved <= (89))
reads as "if spacesmoved is greater than or equal to 83 OR less than or equal to 89"... Think about that for a second. Is there any number that is NOT greater than 83 OR less than 89? The answer is no. EVERY number will satisfy this condition. You would want to use &&, which means "and" like this:
if (spacesmoved >= (83) && spacesmoved <= (89))
"if spacesmoved is greater than or equal to 83 AND less than or equal to 89", which would only work for numbers between 83 to 89 inclusive.
You will also want to remove the semicolons after your "if" statements in that block and the other similar blocks. If you don't, the code inside those conditions won't get executed. That's actually a really tough bug to find when it happens.
Another thing to know is that when you want multiple things to be executed in an "if" condition, you must enclose it in curly braces {}, otherwise, only the first line will be included in the condition, and any following lines will be executed unconditionally. That is another fact that is causing this third problem.
One last thing is that you should try using "else if" and "else" statements. It will help your code flow make more sense. I'm not going to do all the work for you, but this code block should probably look more like this:
if (p1 >= (83) && p1 <= (89))
{
p1 = (82);
System.out.println("Player landed in a lake, player goes back to space " + p1);
}
else if (p1 >= (152) && p1 <= (155))
{
p1 = (151);
System.out.println("Player landed in a lake, player goes back to space " + p1);
}
else if (p1 >= (201) && p1 <= (233))
{
spacesmoved = (spacesmoved / 2);
p1 -= spacesmoved;
System.out.println("Player landed in mud, players turns are cut in half until player gets out");
}
Bonus Tip
You're learning well, and it seems you are thinking of code flow pretty well. Just keep working and learning and you'll get it.
Look into your usage of parentheses. Using them doesn't hurt anything, but you are using them WAY more than you need.
Good luck! And keep learning!
import java.util.Scanner;
public class Blackjack {
class Commands {
static final String yes = "yes";
static final String no = "no";
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//Opponent player2 = new Opponent();
double AiCard1 = 0;
double AiCard2 = 0;
double AiCard3 = 0;
double AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
double card1 = 0;
double card2 = 0;
double card3 = 0;
double card4 = 0;
double total2 = card1 + card2 + card3 + card4;
double total = card1 + card2 + card3;
System.out.println("Hello and Welcome to my custom version of blackjack!");
System.out.println("You will start off with $300");
System.out.println();
System.out.println("Do you want to read the rules before playing?");
System.out.print("Press 1 if yes, press 2 for no");
int choice = input.nextInt();
switch (choice) {
case 1:
System.out.println("You have 4 cards to get as close to 21 as possible. Whoever is closest to 21 wins");
break;
default:
break;
}
int balance = 300;
System.out.println("Your bank balance is $" + balance);
//user places a bet
System.out.println("Place a bet");
int bet = input.nextInt();
System.out.println("You placed a bet of " + bet);
//this is the AI
AiCard1 = Math.random() * 12 + 1;
AiCard1 = Math.round(AiCard1);
AiCard2 = Math.random() + 12 + 1;
AiCard2 = Math.round(AiCard2);
double AiTotal2cards = AiCard1 + AiCard2;
if(AiTotal2cards < 15) {
AiCard3 = Math.random() * 12 + 1;
AiCard3 = Math.round(AiCard3);
AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
}
card1 = Math.random() * 12 + 1;
card1 = Math.round(card1);
System.out.println("Your first card was a " + card1);
System.out.println();
card2 = Math.random() * 10 + 1;
card2 = Math.round(card2);
System.out.println("Your second card was a " + card2);
System.out.println();
System.out.println("Your cards add up to " + (card1 + card2));
System.out.println("Do you want to add another card?");
String answer = input.next();
here:
if(answer.equals(Commands.yes)) {
card3 = Math.random() * 12 + 1;
card3 = Math.round(card3);
System.out.println("Your third card was a " + card3);
System.out.println("Your cards add up to " + (card1 + card2 + card3));
total = card1 + card2 + card3;
if(total > 21) {
System.out.println("You lose");
break here;
}
System.out.println("Do you want to add another card?");
String answer1 = input.next();
if(answer1.equals(Commands.no)){
break here;
}
if(answer1.equals(Commands.yes)) {
card4 = Math.random() * 12 + 1;
card4 = Math.round(card4);
System.out.println("Your fourth card was a " + card4);
System.out.println("Your cards add up to " + (card1 + card2 + card3 + card4));
total2 = card1 + card2 + card3 + card4;
if(total2 > 21) {
System.out.println("You lose");
break here;
}
break here;
}
}
System.out.println("Your total cards were " + total2);
System.out.println("AI total cards were " + AiTotalcard3);
input.close();
}
}
When you run the program I was hoping that the variables at the top would have new numbers saved into them when the user went through the program. Is there a better way to do this because the console output is always 0 for the total.
First lets look at AiTotalcard3:
It shouldn't always output 0 for that, more precisely it will output 0 in the case where AiCard1 + AiCard2 >= 15, which probably happens a lot.
It makes sense if you trace through your actual code. The first thing that happens is those initializers:
double AiCard1 = 0;
double AiCard2 = 0;
double AiCard3 = 0;
double AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
So AiTotalcard3 is initially set to 0. It will remain 0 until you change it, which happens here:
AiCard1 = Math.random() * 12 + 1;
AiCard1 = Math.round(AiCard1);
AiCard2 = Math.random() + 12 + 1;
AiCard2 = Math.round(AiCard2);
double AiTotal2cards = AiCard1 + AiCard2;
if(AiTotal2cards < 15) {
AiCard3 = Math.random() * 12 + 1;
AiCard3 = Math.round(AiCard3);
AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
}
But that only happens if the first two cards add up to less than 15. After that you never touch AiTotalcard3 again.
Your logic can be greatly simplified all around, and also it makes a lot more sense to use int instead of double for the cards, but ignoring all that and sticking to your current style, you could fix this by making sure all paths set AiTotalcard3, for example (again not the cleanest logic but just sticking to your pattern):
if(AiTotal2cards < 15) {
AiCard3 = Math.random() * 12 + 1;
AiCard3 = Math.round(AiCard3);
AiTotalcard3 = AiCard1 + AiCard2 + AiCard3;
} else {
AiTotalcard3 = AiCard1 + AiCard2; // be sure to always set it
}
Now, with all that in mind, you have a similar problem with total2: Not all of your execution paths set the value of total2. It works if you make it up to the 4th card but prior to that you never change it from its initial value of 0. So you're just going to have to go through this with a fine-toothed comb.
One of your fundamental issues is for some reason you're using different variables all over the place for the first 2 cards vs. all the cards. If you just used a single aiTotal and total to accumulate the card totals as you go, you'd avoid most of these issues.
I think your main issue is confusing total and total2. You seem to use both interchangeable in multiple places.
At first, if the user does not pick a third card, total2 will always equal 0 because if the if(answer.equals(Commands.yes)) { is never entered, total2 is never set past the original initialization of 0.
If the user picks a third card but not a fourth, you update the value of total correctly but not total2.
If the user picks a fourth card, then it should work correctly.
Besides the main fixes, here are some tips that you should keep in mind when writing your game:
You mention that the global variables are not recognized, but none of your variables are actually global. You should read up on what exactly that means.
I would suggest using ints or a custom datatype to store card values, as you would never need the decimal places a double provides.
Use loops in your structure to save a lot of code. It will make it cleaner and easier to understand.
Print what the AI is doing. There's no point to having an AI if you can't see its moves.
Anyway, good luck with your game! Programming can be intimidating at first but this is a great start.
My program keeps adding up the score for each player, rather than keeping it separate for example if first player gets 3/5 and the second gets 2/5 the score display for the second player will be 5. I know the answer is probably very simple however I'm not able to find it within the code.
public static void questions(String[] question, String[] answer, int n) {
String[] name = new String[n]; // Player Names
int[] playerscore = new int[n]; // Argument for Score
String[] que = new String[question.length]; //Questions for Loops
int score = 0; // Declare the score
/* --------------------------- For loop for number of players --------------------------- */
for (int i = 0; i < n; i++) {
name[i] = JOptionPane.showInputDialog("What is your name player" + (i + 1) + "?");
JOptionPane.showMessageDialog(null, "Hello :" + name[i] + " Player number " + (i + 1) + ". I hope your ready to start!");
/* --------------------------- Loop in Loop for questions --------------------------- */
for (int x = 0; x < question.length; x++) {
que[x] = JOptionPane.showInputDialog(question[x]);
if (que[x].equals(answer[x])) {
score = score + 1;
} else {
JOptionPane.showMessageDialog(null, "Wrong!");
}
} // End for loop for Question
playerscore[i] = score;
System.out.println("\nPlayer" + (i) + "Name:" + name[i] + "\tScore" + score);
}
}
You will need to reset the score to 0 before each player starts.
Add this after the loop for each player:
score = 0;
Alternatively you could increment the score directly in the array. Just change:
score = score + 1;
to:
playerscore[i] = playerscore[i] + 1;
or simply:
playerscore[i]++;
Assign score=0 after the line
playerscore[i] = score;
Every each and every player is assigned with his score in inner loop. Since score is declared as instance variable it will not differentiate between two different players. In order to have each and every individual player with his own scores, assign score with zero as soon as questions exceeds.
Problem statement
I have another thread on this, but I can't seem to locate it. Basically, I have a Black Jack game. The user is given two random cards (then those cards are added together, and display the total). Then it prompts user if they want another card (They pretty much will want to have a total lower than 21). If they choose "yes," they are given a random card number (they can keep getting a card, but should avoid going over 21), but if they choose "no," the game stops.
Here's the output I should get: [blackjackoutput.jpg]
And here's what I'm getting: [output1.jpg]
Source code:
public class BlackJackGame {
public static void main(String[] args) {
int randomnum1 = (int) (1 + Math.random() * 10);
int randomnum2 = (int) (1 + Math.random() * 10);
int total;
char anotherCard = 'y';
char playAgain;
Scanner input = new Scanner(System.in);
// Prints cards player starts off with
System.out.println("First cards: " + randomnum1 + ", " + randomnum2);
// Sum of the 2 cards
total = randomnum1 + randomnum2;
// Prints Total
System.out.println("Total: " + total);
// Do While Loop that asks question to get lower than 21 or terminate.
while (anotherCard != 'n') {
if (total <= 21) {
System.out.print("Do you want another card? (y/n): ");
anotherCard = input.next().charAt(0);
int randomnum3 = (int) (1 + Math.random() * 10);
System.out.println("Card: " + randomnum3);
total += randomnum3;
System.out.println("Total: " + total);
} else if (total > 21) {
System.out.println("BUST.");
System.out.print("Would you like to play again? (y/n): ");
playAgain = input.next().charAt(0);
}
}
}
}
Issue
When I reach to 21, I choose "no," to stop the program. But, it continues to display the next card and the updated total.
When I "BUST." (Or go over 21). It'll ask me if I want to play. And on separate occasions, I choose "y" and it says "Bust." and asks me if I want to play again (it loops, says "BUST.", and asks me the same question, without being able to end the program). Same thing if I choose "no" it'll say "Bust." and ask me if I can want to play again.
How do you play the game again?
PLEASE HELP!!!
The issue you have is a logic issue here:
if (total <= 21)
{
System.out.print("Do you want another card? (y/n): "); //<--------------
anotherCard = input.next().charAt(0);
int randomnum3 = (int) (1 + Math.random() * 10);
System.out.println("Card: " + randomnum3);
total += randomnum3;
System.out.println("Total: " + total);
You need to check if(anotherCard == 'n') to break out of the loop
Side Note
This blackjack game should have a better distribution of random cards better modeled off a 52 card deck
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.
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.
int [] deck = size 52 array with 4 of each card.
int random = get random number between 0 and 51.
while(deck[random] == -1){
random = get random number between 0 and 51.
}
int card1 = deck[random]
deck[random] = -1;
something like that.. I just did that quickly, hopefully you get the idea.
Here are the tips you requested:
You need to introduce a variable to keep track of your sum. For example, you could initialize it with: int sum = randomnum1 + randomnum2; and keep adding the next card to it inside the loop: sum += randomnum3;
You need to generate 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 of randomnum3 will be unchanged and you will get the same card over and over.
To exit when you get to 21, you would have to use if and possibly break within the loop, once you have added the current card to the sum: if(sum > 21) { break; }
Alternatively, you can set the value of anotherCard to 'n' instead of using a break
You should keep track of which cards the user has already gotten if you want to simulate an actual deck. This is not technically necessary for the program you appear to be writing though.
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!
public static void main(String[] args) {
int card1 = (int) (1 + Math.random() * 10);
int card2 = (int) (1 + Math.random() * 10);
int total = card1 + card2;
System.out.println(String.format("First cards: %d & %d. Total %d", card1, card2, total));
System.out.println();
Scanner input = new Scanner(System.in);
System.out.print("Do you want another card? (y/n): ");
char anotherCard = input.next().charAt(0);
while (anotherCard != 'n' && total < 21) {
int nextcard = (int) (1 + Math.random() * 10);
total += nextcard;
System.out.println(String.format("You drew a %d. Your total is now %d", nextcard, total));
if (total > 21) {
System.out.println("You busted!");
} else {
System.out.print("Do you want another card? (y/n): ");
anotherCard = input.next().charAt(0);
}
}
}