I created this program in my quest to learn Java but every time I run it I get the same cards over and over again. I can't really find the problem, so why aren't my cards random? I don't really get what I'm missing, is my shuffle method incorrect?
package blackjack;
import java.util.Scanner;
public class BlackJack {
public static void main(String[] args) {
System.out.println("Are you ready to play BlackJack?");
System.out.println();
playBlackjack();
System.out.println("Thanks for playing!");
}
static boolean playBlackjack() {
Deck deck;
Hand dealerHand;
Hand playerHand;
deck = new Deck();
dealerHand = new Hand();
playerHand = new Hand();
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
dealerHand.addCard( deck.dealCard() );
playerHand.addCard( deck.dealCard() );
System.out.println();
if (dealerHand.getBlackjackValue() == 21) {
System.out.println("The dealer have the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
System.out.println("You have the " + playerHand.getCard(0)
+ " and the " + playerHand.getCard(1) + ".");
System.out.println();
System.out.println("The dealer has Blackjack! The dealer wins!");
return false;
}
if (playerHand.getBlackjackValue() == 21) {
System.out.println("Dealer has the " + dealerHand.getCard(0)
+ " and the " + dealerHand.getCard(1) + ".");
System.out.println("User has the " + playerHand.getCard(0)
+ " and the " + playerHand.getCard(1) + ".");
System.out.println();
System.out.println("You have Blackjack. You win.");
return true;
}
while (true) {
// User decides whether to hit or stand
System.out.println();
System.out.println();
System.out.println("Your cards are:");
for ( int i = 0; i < playerHand.getCardCount(); i++ )
System.out.println(" " + playerHand.getCard(i));
System.out.println("The total of your hand is " + playerHand.getBlackjackValue());
System.out.println();
System.out.println("The dealer is showing the " + dealerHand.getCard(0));
System.out.println();
System.out.println("Do you hit(type 0) or stand(type 1)? ");
Scanner input = new Scanner(System.in);
int choice = input.nextInt();
if (choice != 0 && choice != 1){
System.out.println("0 or 1 must be inputted to continue ");}
while (choice != 0 && choice != 1);
if ( choice == 1 ) {
break;
}
else {
Card newCard = deck.dealCard();
playerHand.addCard(newCard);
System.out.println();
System.out.println("You hits and your card is the " + newCard);
System.out.println("The total of the hand is now " + playerHand.getBlackjackValue());
if (playerHand.getBlackjackValue() > 21) {
System.out.println();
System.out.println("Fool of a Took! You went over 21 and busted!");
return false;
}
}
}
//User has stood at this point. Poor fool
System.out.println();
System.out.println("You stand. Wouldn't it be nice to sit sometime?");
System.out.println("The dealer's cards are "+ dealerHand.getCard(0) + " and the " + dealerHand.getCard(1));
while (dealerHand.getBlackjackValue() <= 16) {
Card newCard = deck.dealCard();
System.out.println("The dealer hits and gets the " + newCard);
dealerHand.addCard(newCard);
if (dealerHand.getBlackjackValue() > 21) {
System.out.println();
System.out.println("The dealer busted! You win!");
return true;
}
}
System.out.println("The dealer's total is " + dealerHand.getBlackjackValue());
System.out.println();
if (playerHand.getBlackjackValue() == dealerHand.getBlackjackValue()) {
System.out.println("The house always wins on a tie. You lose :(");
return false;
}
else if (dealerHand.getBlackjackValue() >= playerHand.getBlackjackValue()) {
System.out.println("The dealer wins as he has " + dealerHand.getBlackjackValue()
+ " points to your " + playerHand.getBlackjackValue() + "!");
return false;
}
else {
System.out.println("You win because you had " + playerHand.getBlackjackValue()
+ " points while the dealer only had " + dealerHand.getBlackjackValue() + "!");
return true;
}
}
}
package blackjack;
public class Card {
private int suit;
private int rank;
public final static int SPADES = 0, // Codes for the 4 suits.
HEARTS = 1,
DIAMONDS = 2,
CLUBS = 3;
public final static int ACE = 1,
JACK = 11,
QUEEN = 12,
KING = 13;
public Card(int cRank, int cSuit) {
rank = cRank;
suit = cSuit;
}
public int getSuit() {
return suit;
}
public int getRank() {
return rank;
}
public String getSuitString() {
// Return a String representing the card's suit.
// (If the card's suit is invalid, "??" is returned.)
switch ( suit ) {
case SPADES: return "Spades";
case HEARTS: return "Hearts";
case DIAMONDS: return "Diamonds";
case CLUBS: return "Clubs";
default: return "I don't even know";
}
}
public String getRankString() {
switch ( rank ) {
case 1: return "Ace";
case 2: return "2";
case 3: return "3";
case 4: return "4";
case 5: return "5";
case 6: return "6";
case 7: return "7";
case 8: return "8";
case 9: return "9";
case 10: return "10";
case 11: return "Jack";
case 12: return "Queen";
case 13: return "King";
default: return "This is impossible!";
}
}
#Override
public String toString() {
return getRankString() + " of " + getSuitString();
}
}
package blackjack;
public class Deck {
private Card[] deck;
private int cardsUsed;
public Deck() {
deck = new Card[52];
int l = 0;
for ( int suit = 0; suit <= 3; suit++ ) {
for ( int value = 1; value <= 13; value++ ) {
deck[l] = new Card(value,suit);
l++;
}
}
cardsUsed = 0;
}
public void shuffle() {
for ( int i = 51; i > 0; i-- ) {
int rand = (int)(Math.random()*(i+1));
Card temp = deck[i];
deck[i] = deck[rand];
deck[rand] = temp;
}
cardsUsed = 0;
}
public int cardsLeft() {
return 52 - cardsUsed;
}
public Card dealCard() {
if (cardsUsed == 52){
shuffle();}
cardsUsed++;
return deck[cardsUsed - 1];
}
}
package blackjack;
import java.util.*;
public class Hand {
private ArrayList hand;
public Hand() {
hand = new ArrayList();
}
public void clear() {
hand.clear();
}
public void addCard(Card c) {
if (c != null){
hand.add(c);
}
}
public void removeCard(Card c) {
hand.remove(c);
}
public void removeCard(int location) {
if (location >= 0 && location < hand.size()){
hand.remove(location);
}
}
public int getCardCount() {
return hand.size();
}
public Card getCard(int location) {
if (location >= 0 && location < hand.size()){
return (Card)hand.get(location);}
else{
return null;
}
}
public void sortBySuit() {
ArrayList newHand = new ArrayList();
while (hand.size() > 0) {
int pos = 0;
Card c = (Card)hand.get(0);
for (int i = 1; i < hand.size(); i++) {
Card c1 = (Card)hand.get(i);
if ( c1.getSuit() < c.getSuit() ||
(c1.getSuit() == c.getSuit() && c1.getRank() < c.getRank()) ) {
pos = i;
c = c1;
}
}
Object remove = hand.remove(pos);
newHand.add(c);
}
hand = newHand;
}
public int getBlackjackValue() {
int val;
boolean ace;
int cards;
val = 0;
ace = false;
cards = getCardCount();
for ( int i = 0; i < cards; i++ ) {
Card card;
int cardVal;
card = getCard(i);
cardVal = card.getRank();
if (cardVal > 10) {
cardVal = 10;
}
if (cardVal == 1) {
ace = true;
}
val = val + cardVal;
}
if ( ace == true && val + 10 <= 21 ){
val = val + 10;
}
return val;
}
}
It's impossible to tell because you have not shown us the relevant code. However, if your results are not random, it's probably because Deck.dealCard() is not random.
Update
After reading the new code you posted. You are not shuffling your deck after you create it.
It's not random, because Deck::dealCard() is not random.
dealCard is quite strange: when a new Deck is created, cardsUsed is 0, yet you shuffle only if cardsUsed is 52.
public Card dealCard() {
if (cardsUsed == 52){
shuffle();}
cardsUsed++;
return deck[cardsUsed - 1];
}
I think you should move the call to shuffle to the constructor, right after constructing the deck.
Related
Run this code so you can play it aswell.
Rules: Guess the next it's higher or lower card. if you guessed right get a score, if you guessed wrong the game ends.
the issue is that "Deck.getCards().size()" size of the deck removes 2 cards each time. I believe that the card that I print if guessed right does show another card instead of the one I had to guess before.
Can someone see what is wrong.
Bonus question: Ace in my game is the highest value card. But I somehow managed to lose while guessing lower when having a ace (maybe this has to do with that I believe I had ace because of what I outprint) if someone can help out with this one I would be so thankfull..
package CardGame;
import java.util.Scanner;
import java.util.*;
public class Game {
// score int
private static int score;
// currentCard : Card
private static Card currentCard;
// Next Card
private static Card nextCard;
// Scanner
private static Deck deck;
private static Scanner sc = new Scanner(System.in);
// Main
public static void main(String[] args) {
deck = new Deck();
currentCard = deck.getNextCard();
Game.gameTurn();
}
// get turn method
public static void gameTurn() {
// System.out.println(Deck.getCards().size());
score = 0;
System.out.print("your current card is " + currentCard.getName() + " is it higher or lower? > ");
while (true) {
String answer = sc.nextLine();
Card nextCard = deck.getNextCard();
if (answer.equals("higher") && nextCard.isHigherOrEqual(currentCard)) {
correct();
} else if (answer.equals("lower") && !nextCard.isHigherOrEqual(currentCard)) {
correct();
} else {
gameOver();
break;
}
}
}
// correct method
public static void correct() {
score++;
System.out.println("You are right! your score is: " + score);
System.out.println(Deck.getCards().size() + " total cards");
nextCard = Deck.getNextCard();
System.out.println("your current card is " + nextCard.getName());
}
// Game over Method
public static void gameOver() {
System.out.println("you lost");
System.out.println("total score is " + score + "!");
System.out.println(Deck.getCards().size() + " total cards");
}
}
package CardGame;
import java.util.ArrayList;
import java.util.Collections;
public class Deck {
// cards = Card = new ArrayList<>()
private static ArrayList<Card> cards = new ArrayList<>();
// Deck Method
public Deck() {
for (int i = 0; i < 4; i++) {
String suits;
switch (i) {
// hart
case 0:
suits = "Hearts";
break;
// ruit
case 1:
suits = "Diamonds";
break;
// schoppen
case 2:
suits = "Spades";
break;
// klaveren
case 3:
suits = "Clubs";
break;
default:
suits = "";
break;
}
for (int j = 2; j <= 10; j++) {
int value = j;
String name = j + " of " + suits;
Card c = new Card(suits, name, value);
cards.add(c);
}
// add 1.3 tot 1.11
Card jack = new Card(suits, "Jack of " + suits, 11);
cards.add(jack); // JACK
Card queen = new Card(suits, "Queen of " + suits, 12);
cards.add(queen); // QUEEN
Card king = new Card(suits, "King of " + suits, 13);
cards.add(king); // KING
Card ace = new Card(suits, "Ace of " + suits, 14);
cards.add(ace); // ACE
}
// 1.11 shuffle cards
Collections.shuffle(cards);
}
// getNextCard() : Card
public static Card getNextCard() {
Card nextCard = cards.remove(0);
return nextCard;
}
// getCards() : ArrayList <card>
public static ArrayList<Card> getCards() {
return cards;
}
}
package CardGame;
public class Card {
// Suit String
private String suit;
// Name String
private String name;
// Value int
private int value;
// Card constructor
public Card(String suit, String name, int value) {
this.value = value;
this.name = name;
this.suit = suit;
}
public int getValue() {
return value;
}
// toString Method
public String toString() {
return suit;
}
public String getName() {
return name;
}
// isHigherorEqual Method
public boolean isHigherOrEqual(Card c) {
if (this.value >= c.getValue()) {
return true;
} else {
return false;
}
}
}
You are using getNextCard twice before checking the result. So it will remove 2 cards. If you want to update the current card, change the nextCard to currentCard in Correct method.
public static void correct() {
score++;
System.out.println("You are right! your score is: " + score);
System.out.println(Deck.getCards().size() + " total cards");
currentCard = Deck.getNextCard();
System.out.println("your current card is " + currentCard.getName());
}
Remove nextCard = Deck. .... from correct method.
Move
String answer = sc.nextLine();
Card nextCard = deck.getNextCard();
System.out.println("your current card is " + nextCard.getName());
I'm trying to get my program to take multiple different return statements so i can have a win split and lose rather than just win or lose and cant seem to figure out how to do it. My program is made to be able to have either you win and it doubles your bet that you made. If you tie you get your money back. if you lose you lose your bet. Ive gotten win and lose to work previously with using a booelean and returning true or false but needed a way to add in a way to do split.
I've tried multiple methods I've seen online but to no avail any help would be appreciated.
//Import Random Number Generator
import java.util.Random;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private int sum;
private int numAces;
private static Random gen = new Random();
private String Win;
private String Lose;
private String Split;
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public String getWin(BlackJackPlayer other) {
if(sum > 21){
Win = "Win";
}
else if(sum < other.getSum()){
Lose = "Lose";
}
else if(sum == other.getSum()){
Split = "Split";
}
return Win;
}
}//end main
import java.util.Scanner;
class BlackJackGame{
public static void main(String args[]){
BlackJackPlayer you = new BlackJackPlayer();
BlackJackPlayer enemy = new BlackJackPlayer();
int chips = 100;
int bet;
int winnings;
int multiply = 2;
String qORc;
Scanner in = new Scanner(System.in);
String choice;
do{
you.setHand();
enemy.setHand();
you.hit();
enemy.hit();
enemy.hit();
System.out.println("Chips: " + chips);
System.out.println("How much do you want to bet");
bet = in.nextInt();
chips -= bet;
System.out.println("You bet: " + bet + ", You now have " + chips + " chips");
do{
System.out.println("Your Cards: " + you.getHand());
System.out.println("(H)it or (S)tand");
choice = in.next();
if(choice.equalsIgnoreCase("h")){
you.hit();
}
}while(choice.equalsIgnoreCase("h"));
while(enemy.getSum() < 16){
enemy.hit();
}
System.out.println(you.getWin());
if(you.getWin()){
System.out.println("You Win");
System.out.println(enemy.getHand());
winnings = bet * multiply;
chips += winnings;
System.out.println("You now have: " + chips + " chips!");
}
else{
System.out.println("You Lose");
System.out.println(enemy.getHand());
System.out.println("You now have: " + chips + " chips.");
}
System.out.println("(C)ontinue or (Q)uit");
qORc = in.next();
}while(chips > 0 && qORc.equalsIgnoreCase("c"));
}//end main
}//end class
I expect to be able to get different return statements that way I can actually set a win aspect a lose aspect but also a split aspect if both players tie.
You have three results to return which are: WIN, LOSE and TIE right?
In that case you have to use three different variables like,
public String Win = "Win",Lose = "Lose",Split = "Split";
and use other variable to store result like result and return this result in getWin(). See below code:
import java.util.Random;
import java.util.Scanner;
class BlackJackPlayer{
//Keep the data secure by using private
private String hand;
private int sum;
private int numAces;
private static Random gen = new Random();
public String Win = "Win",Lose = "Lose",Split = "Split";
private String result = "";
private final int ACE = 1;
private final int JACK = 11;
private final int QUEEN = 12;
private final int KING = 13;
//constructor
public BlackJackPlayer(){
hand = "";
sum = 0;
numAces = 0;
}
//Getter for hand variable
public String getHand(){
return hand;
}
public String setHand(){
hand = " ";
return hand;
}
//Getter for sum variable
public int getSum(){
return sum;
}
public void hit(){
//local variable
int currentCard = gen.nextInt(13) + 1;
if(currentCard > ACE && currentCard < JACK){
sum += currentCard;
hand += currentCard + " ";
}
else if(currentCard == ACE){
sum += 11;
numAces++;
hand += "A ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == QUEEN){
sum += 10;
hand += "Q ";
}
else if(currentCard == KING){
sum += 10;
hand += "K ";
}//Ends Else If
//Is Ace 1 or 11
if(sum > 21 && numAces > 0){
numAces--;
sum -= 10;
}
}//ENDS HIT
public String getWin(BlackJackPlayer other) {
if(sum > 21){
result = Win;
}
else if(sum < other.getSum()){
result = Lose;
}
else if(sum == other.getSum()){
result = Split;
}
return result;
}
}//end main
class BlackJackGame{
public static void main(String args[]){
BlackJackPlayer you = new BlackJackPlayer();
BlackJackPlayer enemy = new BlackJackPlayer();
int chips = 100,bet,winnings,multiply = 2;
String qORc;
Scanner in = new Scanner(System.in);
String choice;
do{
you.setHand();
enemy.setHand();
you.hit();
enemy.hit();
enemy.hit();
System.out.println("Chips: " + chips);
System.out.println("How much do you want to bet");
bet = in.nextInt();
chips -= bet;
System.out.println("You bet: " + bet + ", You now have " + chips + " chips");
do{
System.out.println("Your Cards: " + you.getHand());
System.out.println("(H)it or (S)tand");
choice = in.next();
if(choice.equalsIgnoreCase("h")){
you.hit();
}
}while(choice.equalsIgnoreCase("h"));
while(enemy.getSum() < 16){
enemy.hit();
}
String result = you.getWin(enemy);
System.out.println(result);
if(result == you.Win){
System.out.println("You Win");
System.out.println(enemy.getHand());
winnings = bet * multiply;
chips += winnings;
System.out.println("You now have: " + chips + " chips!");
}
else if (result == you.Lose){
System.out.println("You Lose");
System.out.println(enemy.getHand());
System.out.println("You now have: " + chips + " chips.");
}else{
System.out.println("You Split");
}
System.out.println("(C)ontinue or (Q)uit");
qORc = in.next();
}while(chips > 0 && qORc.equalsIgnoreCase("c"));
}//end main
}
I have a Java game in which you play Blackjack, and I use a Scanner to take input for things like "hit" and "stay." When I run it, the Windows wait cursor shows up and doesn't go away until I close the program. I tried to use Scanner's close() method, but that throws an exception.
here's the code:
import java.util.Scanner;
import java.util.ArrayList;
public class CardGame {
public static ArrayList<Card> dealIn(ArrayList<Card> hand) {
Card a = new Card();
Card b = new Card();
hand.add(a);
while (hand.size() < 2) {
if (!b.equals(a)) {
hand.add(b);
} else
dealIn(hand);
}
return hand;
}
public static int calcScore(ArrayList<Card> hand) {
int sum = 0;
int aces = 0;
for (Card c : hand) {
if (c.getCardValue().getFace().equals("A")) {
aces++;
} else {
sum += c.getCardValue().getNumeric();
}
}
while (aces > 0) {
aces--;
if (sum <= 10) {
sum += 11;
} else {
sum += 1;
}
}
return sum;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Welcome to Blackjack!\n");
ArrayList<Card> playerhand = new ArrayList<Card>();
ArrayList<Card> dealerhand = new ArrayList<Card>();
dealIn(playerhand);
for (int i = 0; i < 2; i++) {
Card a = new Card();
if ((!playerhand.contains(a)) && (!dealerhand.contains(a))) {
dealerhand.add(a);
}
}
// System.out.println("DEALER HAND: [hidden]" + " and " +
// dealerhand.get(1));
System.out.println("TEST DEALER HAND: " + dealerhand);
System.out.println("Your hand: " + playerhand);
while (!isBusted(playerhand)) {
System.out.println("Your score is " + calcScore(playerhand) + ". Hit or stay?");
String hOrS = in.nextLine();
if (hOrS.equalsIgnoreCase("hit")) {
hit(playerhand);
System.out.println(playerhand);
if (isBusted(playerhand)) {
System.out.println("Your score is " + calcScore(playerhand) + "! YOU LOSE");
break;
}
// System.out.println(playerhand);
}
if (hOrS.equalsIgnoreCase("stay")) {
while (calcScore(dealerhand) <= 17) {
Card n = new Card();
if (!dealerhand.contains(n)) {
dealerhand.add(n);
// System.out.println(dealerhand);
}
}
}
if (isBusted(dealerhand) || (!isBusted(playerhand) && (calcScore(playerhand) > calcScore(dealerhand)))) {
System.out.println("DEALER HAND: " + dealerhand);
System.out.println("YOUR HAND: " + playerhand);
System.out.println("YOU WIN");
// break;
} else {
System.out.println(dealerhand);
System.out.println("YOU LOSE");
break;
}
}
}
}
Is it possible to fix this?
I'm learning Java for my own and i have this problem:
I created a poker program, and every time, both the AI and I draw nothing but the Ace of Spades (5 each) every round. How can I fix this?
import java.io.IOException;
import java.util.Scanner;
public class poker {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) throws IOException {
int score1 = 0,score2 = 0;
for (int i=0; i<10; i++) {
int[][] previous_cards = new int[0][2];
int[][] hand1 = generate_hand(previous_cards);
int[][] sorted1 = sort_hand(hand1);
System.out.println("Round "+(i+1)+": ");
System.out.print(" Your hand: ");
print_hand(sorted1);
int identify_hand1 = identify_hand(sorted1);
System.out.print(" ");
print_identify_hand(identify_hand1);
System.out.println();
int[][] hand2 = generate_hand(hand1);
int[][] sorted2 = sort_hand(hand2);
System.out.print(" Computer hand: ");
print_hand(sorted2);
int identify_hand2 = identify_hand(sorted2);
System.out.print(" ");
print_identify_hand(identify_hand2);
System.out.println();
int compared = compare_hands(sorted1,sorted2);
if (compared==-1)
System.out.println(" You win this round!");
else if (compared==1)
System.out.println(" The computer wins this round!");
else System.out.println("Draw!");
score1 += (compared<0)?1:0;
score2 += (compared>0)?1:0;
System.out.println(" Score: You:"+score1+" - Computer:"+score2);
input.nextLine();
}
if (score1<score2)
System.out.println("The computer won with: "+score2+"-"+score1+".");
else if (score1==score2)
System.out.println("Draw: "+score1+"-"+score2+".");
else System.out.println("You won with: "+score1+"-"+score2+".");
}
public static int[][] generate_hand(int[][] previous_cards) {
int[][] hand = new int[5][2];
return hand;
}
public static int[] generate_card() {
int[] card = new int[2];
card[0] = (int) (Math.random()*13 + 2);
card[1] = (int) (Math.random()*4 + 1);
return card;
}
public static int compare_2_cards(int[] card1, int[] card2) {
return 0;
}
public static void print_hand(int[][] hand) {
System.out.print(card_to_String(hand[0])+", ");
System.out.print(card_to_String(hand[1])+", ");
System.out.print(card_to_String(hand[2])+", ");
System.out.print(card_to_String(hand[3])+", ");
System.out.print(card_to_String(hand[4]));
}
public static String card_to_String(int[] c) {
String card = "";
if (2<=c[0] && c[0]<=10)
card += c[0];
else if (c[0]==11) card += "Jack";
else if (c[0]==12) card += "Queen";
else if (c[0]==13) card += "king";
else card += "Ace";
card += " of ";
if (c[1]==1) card += "hearts";
else if (c[1]==2) card += "diamonds";
else if (c[1]==2) card += "clubs";
else card += "spades";
return card;
}
public static int[][] sort_hand(int[][] hand) {
int[][] sorted = new int[5][2];
return sorted;
}
public static void print_identify_hand(int identify_hand) {
if (identify_hand==1)
System.out.print("(straight flush)");
else if (identify_hand==2)
System.out.print("(four of a kind)");
else if (identify_hand==3)
System.out.print("(full house)");
else if (identify_hand==3)
System.out.print("(four of a kind)");
else if (identify_hand==4)
System.out.print("(flush)");
else if (identify_hand==5)
System.out.print("(straight)");
else if (identify_hand==6)
System.out.print("(three of a kind)");
else if (identify_hand==7)
System.out.print("(two pairs)");
else if (identify_hand==8)
System.out.print("(one pair)");
else
System.out.print("(nothing - high hand comparison)");
}
public static int compare_hands(int[][] hand1,int[][] hand2) {
// IMPLEMENT: compare 2 cards
return 1;
}
public static int identify_hand(int[][] hand) {
if (hand[0][1]==hand[1][1] && hand[1][1]==hand[2][1] && hand[2][1]==hand[3][1] && hand[3][1]==hand[4][1] && // compare that they have the same suit
hand[0][0]+1==hand[1][0] && hand[1][0]+1==hand[2][0] && hand[2][0]+1==hand[3][0] && hand[3][0]+1==hand[4][0]) // compare card numbers
return 1;
if (hand[0][0]==hand[1][0] && hand[1][0]==hand[2][0] && hand[2][0]==hand[3][0]) // compare card numbers
return 2;
if (hand[1][0]==hand[2][0] && hand[2][0]==hand[3][0] && hand[3][0]==hand[4][0]) // compare card numbers
return 2;
return 9;
}
}
Your int[][] hand objects are empty.
The generate_hand method returns an empty array, sort_hand returns another empty array, the other methods don't alter the array at all.
You end up passing empty (for int arrays, that means that each index contains 0) arrays to card_to_String, which then displays the result for c[0] == 0 and c[1] == 0, you got it...this is Ace of spades.
Everything else works fine except I run into an issue of printing out the card the player (if they 'hit' ) as I don't know what card the player draws and which player draws what card, it starts at 8 as the first 7 cards are drawn but I don't know what player gets what and how many. So I tried to have a method to print out the hand of each player but I'm having a LOT of trouble with that could use some help. I want to print the cards the players get in my output. I'll post my Card, Player, and BlackJackGame class as my Dealer class is very similar to player.
Card.java
import java.util.Random;
public class Card
{
private String suit, rank;
private int value;
public Card(String suit, String rank)
{
this.suit = suit;
this.rank = rank;
}
public String getRank()
{
return rank;
}
public int Value()
{
if(rank.equals("2"))
{
value=2;
}
else if(rank.equals("3"))
{
value=3;
}
else if(rank.equals("4"))
{
value=4;
}
else if(rank.equals("5"))
{
value=5;
}
else if(rank.equals("6"))
{
value=6;
}
else if(rank.equals("7"))
{
value=7;
}
else if(rank.equals("8"))
{
value=8;
}
else if(rank.equals("9"))
{
value=9;
}
else if(rank.equals("10"))
{
value=10;
}
else if(rank.equals("A"))
{
Random rand = new Random();
int count = rand.nextInt(1) +1;
if(count == 1)
{
value=11;
}
else
value= 1;
}
else if(rank.equals("Q"))
{
value=10;
}
else if(rank.equals("J"))
{
value=10;
}
else if(rank.equals("K"))
{
value=10;
}
return value;
}
public String toString()
{
return(rank + " of " + suit);
}
}
Player.java
public class Player
{
private int cValue;
private int cCount; //Card count used to count how many 'cards' added
Card[] deck= new Card[52];
private int sum;
public Player()
{
cCount=0;
}
public Card addCard(Card a)
{
deck[cCount] = a;
cCount++;
return a;
}
public int getcCount()
{
return cCount;
}
public int getValue()
{
int total=0;
for(int i=0; i < cCount; i++)
{
total += deck[i].Value();
}
return total;
}
BlackJackGame.java
public class BlackJackGame
{
public static void main(String [] args)
{
Card[] deck = new Card[52];
Player[] player = new Player[3];
int loopcount=0;
String p1result = " ", p2result = " ", p3result = " ", p4result = " ", dresult = " ";
String[] suit = {"Hearts", "Clubs", "Spades", "Diamonds"};
String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
for(int i=0; i<13; i++)
{
for(int x=0; x<4;x++)
{
deck[loopcount] = new Card(suit[x], rank[i]);
loopcount++;
}
}
System.out.println("Shuffling...");
for(int i=0; i< deck.length; i++) //Shuffle
{
Card tmp = deck[i];
int count= (int)(Math.random()* deck.length);
deck[i] = deck[count];
deck[count] = tmp;
}
Player player1 = new Player();
Player player2 = new Player();
Player player3 = new Player();
System.out.println("Welcome to our BlackJackGame!");
System.out.println("Welcome Dealer!");
Dealer dealer = new Dealer();
System.out.println("Let's deal the cards!");
player1.addCard(deck[0]);
player2.addCard(deck[1]);
player3.addCard(deck[2]);
System.out.println("And now the Dealer gets his card...");
dealer.addCard(deck[3]);
System.out.println("Now we get our second cards!");
System.out.println("Okay Dealer, deal out the cards!");
player1.addCard(deck[4]);
player2.addCard(deck[5]);
player3.addCard(deck[6]);
dealer.addCard(deck[7]);
int count =8;
int i=0;
do
{
p1result = "";
p2result = "";
p3result = "";
dresult = "";
int dvalue = dealer.getValue();
int p1value = player1.getValue();
int p2value = player2.getValue();
int p3value = player3.getValue();
while(p1value < 17) //hit
{
player1.addCard(deck[count]);
count++;
p1value = player1.getValue();
}
if(p1value > 21)
{
p1result = "Bust!";
}
if(p1value <21 && p1value >17)//stand
{
}
while(p2value < 17)//hit
{
player2.addCard(deck[count]);
count++;
p2value = player2.getValue();
}
if(p2value > 21) //bust
{
p2result = "Bust!";
}
if(p2value <21 && p2value >17) //stand
{
}
while(p3value < 17) //hit
{
player3.addCard(deck[count]);
count++;
p3value = player3.getValue();
}
if( p3value > 21)
{
p3result = "Bust!";
}
if(p3value <21 && p3value >21) //stand
{
}
while(dvalue < 17)
{
dealer.addCard(deck[count]);
count++;
dvalue = dealer.getValue();
}
if(dvalue > 21) //Bust
{
p1value = player1.getValue();
p2value = player2.getValue();
p3value = player3.getValue();
if(p1value == 21 || p1value <21)
{
p1result = "Win!";
}
if(p2value == 21 || p2value <21)
{
p2result = "Win!";
}
if(p3value == 21 || p3value <21 )
{
p3result = "Win!";
}
}
if(dvalue < 21 && dvalue >= 17) //For Dealer values in between
{
p1value = player1.getValue();
p2value = player2.getValue();
p3value = player3.getValue();
dvalue = dealer.getValue();
if(p1value == dvalue)
{
p1result = "Push!";
}
if(p1value > dvalue)
{
p1result = "Win!";
}
if(p1value < dvalue)
{
p1result = "Lose!";
}
if(p2value == dvalue)
{
p2result = "Push!";
}
if(p2value > dvalue)
{
p2result = "Win!";
}
if(p2value < dvalue)
{
p2result = "Lose!";
}
if(p3value == dvalue)
{
p3result = "Push!";
}
if(p3value > dvalue)
{
p3result = "Win!";
}
if(p3value < dvalue)
{
p3result = "Lose!";
}
}
if(dvalue == 21 )
{
p1value = player1.getValue();
p2value = player2.getValue();
p3value = player3.getValue();
dvalue = dealer.getValue();
if(p1value == dvalue)
{
p1result = "Push!";
}
if(p1value < dvalue || p1value > dvalue)
{
p1result = "Lose!";
}
if(p2value == dvalue)
{
p2result = "Push!";
}
if(p2value < dvalue || p2value > dvalue)
{
p2result = "Lose!";
}
if(p3value == dvalue)
{
p3result = "Push!";
}
if(p3value < dvalue || p3value > dvalue)
{
p3result = "Lose!";
}
}
System.out.println("The BlackJack Game is Complete: ");
System.out.println("Results: ");
System.out.println("Dealer: " +deck[3] + " " + deck[7] + " " +("total of " +dealer.getValue() ));
System.out.println("Player1: " +deck[0] + " " + deck[4] + " "+("total of " +player1.getValue() )+ ": " +p1result);
System.out.println("Player2: " +deck[1] + " " + deck[5] + " "+("total of " +player2.getValue() )+ ": " +p2result);
System.out.println("Player3: " +deck[2] + " " + deck[6] + " "+("total of " +player3.getValue() )+ ": " +p3result);
i++;
}
while(i <1);
}
}
Example Output:
BlackJack Game is Complete!
Results!
Dealer : 6 of Clubs 8 of Spades total 17
Player1: 2 of Clubs 2 of Spades total 16 Lose!
Player2: Q of Hearts Q of Spades total 20 Win!
Player3: A of Spades 6 of Hearts total 17 Push!
// The Problem is when the cards are printed , I print out the first two cards each player has and the dealer which are known. The problem I run into is if the player or dealer 'hits' as you can see with Player 1 I don't know which cards are hit/ and which player has them and was wondering how to have a method in the Player class that would print the hand of each player including the dealer and the cards they have for my output. That is what I need help with. Everything else works fine.
First, I would suggest using a switch statement instead of all those else ifs for rank, it'll be a lot neater :)
Second, in Blackjack an Ace doesn't have a "random" value of either 1 or 11; it is an 11 unless it being an 11 makes the player bust.
Third, I would consider using a list for the deck. Then all you need to do is "shuffle" the list and when you deal a card, remove the top card from the list and add it to the player's hand. (see Collections.Shuffle)
Now to address the initial question, you should have a List hand in the player class. Then add an extension method to the player class to print the hand; it should look something like this:
public void printHand() {
ListIterator<Card> it = hand.listIterator();
if(it.hasNext())
System.out.print(it.next());
while(it.hasNext())
System.out.print(", " + it.next());
System.out.println();
}