import java.util.Random;
import java.util.Stack;
import java.util.Scanner;
public class Blackjack {
public static void main(String[] args) {
int cardValue; /* card value is from 2 to 11 */
int MaxCard = 50;
Stack < Integer > Player1 = new Stack < Integer > ();
Stack < Integer > Addition = new Stack < Integer > ();
Stack < Integer > Dealer = new Stack < Integer > ();
Scanner keyboard = new Scanner(System.in);
String input;
Random r = new Random();
System.out.println("Welcome to Mitchell's blackjack program!");
for (int a = 1; a <= 2; a++) { // Start's the game by assigning 2 cards each, to the players
int Player1draw = 2 + r.nextInt(11);
int Dealerdraw = 2 + r.nextInt(11);
//System.out.print("\nPushing in " + Player1draw + " to Player 1."); - used for checking
Player1.push(Player1draw);
//System.out.print("\nPushing in " + Dealerdraw + " to Dealer."); - used for checking
Dealer.push(Dealerdraw);
}
Integer pop1 = (int) Player1.pop();
System.out.print("\nYou get a " + pop1);
Integer pop2 = (int) Player1.pop();
System.out.print(" and " + pop2);
int sum = pop1 + pop2;
System.out.print("\nYour total is " + sum);
if (sum > 21) {
System.out.print("\nYou LOST! ");
System.exit(0);
}
Integer pop3 = (int) Dealer.pop();
System.out.print("\nThe dealer has a " + pop3 + " showing, and a hidden card.\n");
Integer pop4 = (int) Dealer.pop();
System.out.print("\nHis total is hidden, too.\n");
for (int i = 0; i < MaxCard; i++) {
System.out.print("\nWould you like to \"hit\" or \"stay\"? ");
input = keyboard.next();
if (input.equals("hit")) {
int draw2 = 2 + r.nextInt(11); // draw -> 'hit' for another card
int sum3 = sum + draw2;
System.out.print("\nYou drew a " + draw2);
System.out.print("\nYour total is " + (sum3) + ".");
if ((sum + draw2) > 21) {
System.out.print("\nThe Dealer WON and you LOST!");
System.exit(0);
}
} else if (input.equals("stay")) {
System.out.print("\nOkay, dealer's turn.");
System.out.print("\nHis hidden card was a " + pop4);
int sum2 = pop3 + pop4;
System.out.print("\nHis total was " + sum2);
if (sum2 > 21) {
System.out.print("\nThe Dealer LOST and you WON!");
System.exit(0);
}
}
}
}
}
So when the code runs, what it does is that it will draw 2 cards for Player1 (both of the card is shown) and the dealer(1 of the card is shown). It will then display the total number of points player1 has. So after i press hit, to draw another card, it calculates the total value just fine because it sums up the current drawn card value into the previous 2 card.
Now the problem is, how can I code it so whenever I type the 'hit' button again it will than add up the previous 3 cards and the newly drawn card?
int sum = 0;
for(Integer card : Player1)
sum += card;
if(sum > 21) system.err.println("Over 21; you lost");
Looking for something like that... ?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.