Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

I need help creating a twoPlayerBlackJack method?

Posted on 2011-09-15
11
Medium Priority
?
397 Views
Last Modified: 2012-05-12
Card class:

public class Card
{
   
    private String rank;//card rank: a number between 2 and 10, or Jack, Queen, King or Ace
    private char suit;//card suit: S,C,H,or D
    private static String[] Ranks={"2","3","4","5","6","7","8","9","10","Jack","Queen","King","Ace"};
    private static char[] Suites={'C','H','D','S'};
     
    /**
     * Default constructor: sets card rank to 2 and card suit to H
     */
    public Card()
    {
        rank="2";
        suit='H';
       
    }
   
    /**
     * Class constructor: sets card rank and suit to provided values.
     */
    public Card(String rank, char suit)
    {
        this.rank=rank;
        this.suit=suit;
    }
   
    /**
     * Gets the rank
     */
    public String getRank()
    {
        return rank;
    }
   
    /**
     * Gets the suit
     */
    public char getSuit()
    {
        return suit;
    }
   
    /**
     * Sets the rank
     */
    public void setRank(String rank)
    {
        this.rank=rank;
    }
   
    /**
     * Sets the suit
     */
    public void setSuit(char suit)
    {
        this.suit=suit;
    }
    /**
     * Returns an array of possible card ranks
     */
    public static String[] getPossibleRanks()
    {
        return Ranks;
    }
    /**
     * Returns an array of possible card suits
     */
   
    public static char[] getPossibleSuits()
    {
        return Suites;
    }
   
    /**
     * Returns string representation of the card that looks as follows:
     * 2 of Hearts, 3 of Spades, Jack of Diamonds, etc.
     */
    public String toString()
    {String suitName = "";
        switch (suit){
        case 'H':
         suitName = rank + " of Hearts";
            break;
         case 'S':
            suitName = rank + " of Spades";
             break;
              case 'D':
                suitName = rank + " of Diamonds";
                  break;
                  case 'C':
                   suitName = rank + " of Clubs";


    }
return suitName;
}
}

DeckOfCards class:

mport java.util.Random;
import java.util.ArrayList;
public class DeckOfCards
{
    private ArrayList<Card> deck;
    Random getRandom = new Random();
   
    /**
     * Default constructor creates an Array List of Cards and populates it with 52 different cards
     */
    public DeckOfCards()
    {
        deck = new ArrayList<Card>();
        resetDeckOfCards();
    }

    /**
     * Remove all leftover cards from the ArrayList of Cards called deck
     * Populate an empty deck with 52 new cards...
     */
    public void resetDeckOfCards()
    {
       String[] ranks = Card.getPossibleRanks();
       char[] suites = Card.getPossibleSuits();

  for (int i = 0; i < Card.getPossibleRanks().length ; i++)
       {
           for (int j = 0; j < Card.getPossibleSuits().length; j++)
           {
              deck.add(new Card(ranks, suites[j]));
           }
       }
    }

    /**
     * Remove random card of arraylist of cards and return value from method
     */
    public Card getCard()
    {
       if (deck.isEmpty())
            resetDeckOfCards();
       return deck.remove(getRandom.nextInt(deck.size()));
    }

    /**
     * Return an ArrayList of specified size (i.e. returned cards are being removed from the deck).
     */
    public ArrayList<Card> getHand(int size)
    {
        ArrayList<Card> hand = new ArrayList<Card>();
        for (int i = 0; i < size; i++)
        {
            hand.add(this.getCard());
        }
        return hand;
       
    }

}

TwoPlayerBlackJack class:

import java.util.ArrayList;
import java.util.Scanner;
import java.util.Random;
/**
 * Write a description of class TwoPlayerBlackJack here.
 *
 * @author (your name)
 * @version (a version number or a date)
 */
public class TwoPlayerBlackJack
{
   
    private String rank;
    private ArrayList<Card> blackJack;
    private char suit;
   
    /**
     * Constructor for objects of class TwoPlayerBlackJack
     */
    public TwoPlayerBlackJack()
    {
       String[] ranks = Card.getPossibleRanks();
       char[] suites = Card.getPossibleSuits();
       blackJack = new ArrayList<Card>();
  for (int i = 0; i < Card.getPossibleRanks().length ; i++)
       {
           for (int j = 0; j < Card.getPossibleSuits().length; j++)
           {
              blackJack.add(new Card(ranks, suites[j]));
           }
       }
    }

    /**
     * The method takes an object of class Card and return an integer that represents the value of that card.
     * The values of the cards are determines as follows:
     * two is 2, three is 3, ...., nine is 9, ten is 10,  jacks, queens and kings are all 10.
     * Ace could be either 1 or 11 but for this method we will assume that the value Ace is always 1
     */
    public int getCardValue(Card c){
String rank = c.getRank();

int value = -1;
try {
value = new Integer(rank);
}catch(Exception ex){
if(rank.equals("Ace"))value = 1;
else{ value = 10;

}

}
return value;
}

/**
 * Given a hand cards (i.e. ArrayList of Cards) return an integer value that corresponds to the hand value
 * (i.e. sum of all card values).
 */
public int computeHandValue(ArrayList <Card> hand)
{
 
int sum = 0;
int numAces = 0;

for(Card c: hand){
  int value = getCardValue(c);
   sum += value;
 if(c.getRank().equals("Ace"))
 numAces++;

}
 if(sum<12 && numAces >0)sum += 10;  
   
    return sum;

}

/**
 * Method display hand value display the value of each card followed by the hand value
 */
public void printHandValue(ArrayList <Card> hand)
{
    System.out.println(computeHandValue(hand));
}

/**
 * Method that takes two Array Lists of Cards (i.e. two card hands) and determines the winner
 * of the BlackJack game.
 * 1 – the first hand won the game
 * 0 – nobody won, it is a push
 * -1 – the first hand lost the game
 */
public int isWinner(ArrayList <Card> hand01, ArrayList <Card> hand02)
{

if(computeHandValue(hand01) > 21) return -1;

if(computeHandValue(hand02)  > 21) return 1;

if(computeHandValue(hand01) > computeHandValue(hand02)) return 1;
else  if(computeHandValue(hand01) == computeHandValue(hand02)) return 0;
else return -1;
}  

/**
 * Method that returns true if players would like to play another game, and false otherwise.
 */


public boolean toContinue()
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Would you like to play again? Answer yes or no");
String line = keyboard.nextLine();
if(line.trim().toLowerCase().equals("no"))
return false;
return true;
}

/**
 * Displays the following information: first hand, second hand, and the outcome of the game (i.e. which hand won)
 * 1. Create and initialize a new object of class DeckOfCards
 * 2. While method toContinue returns true repeat the following steps:
 * 3. Generate two random numbers: size01 and size02, values between 3 and 10
 * 4. Get two hands of cards one of size size01 and another of size size02
 * 5. Display the following info.
 * (a) first hand info
 * (b) second hand info
 * (c) outcome of the game(i.e. which hand won)
 */
public void twoPlayerBlackJack()
{
int size01,size02;
DeckOfCards myDeck = new DeckOfCards();
while(toContinue()==true)
{
Random generator = new Random();
size01= generator.nextInt();
size02 = generator.nextInt();
printHandValue();
isWinner();
}

}
}
0
Comment
Question by:ryanbecker24
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
11 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 36544701


I don't see a method which creates your Hand - arbitrarily select Cards form the deck - dp you have such method - to create Hands ?
0
 

Author Comment

by:ryanbecker24
ID: 36544730
I don't know. I am just following the methods that my instructor told us to write. I don't think I am allowed to anything different.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36544800

You don' need to write ==true for sure (I corrected this part below).

Now think - your Hand is ArrayList of cards - so first you need t create the ArrayList  for each player
and then drwa cards from the deck - and then how many tim,es you draw - thios is
the main point odfstratgy in black jack - ok instead of it you just drwa
size 01 for oner hand and size02 cards for the other hand - but you still have to have the mthod to draw
card from the deck and this method you should call siz01 for fisrt hand and size02 for the second hand

When you end drawing the cards on both hands then you can compare
so this method is still a lot to do.


public void twoPlayerBlackJack()

{
int size01,size02;
DeckOfCards myDeck = new DeckOfCards();
while(toContinue())
{
Random generator = new Random();
size01= generator.nextInt();
size02 = generator.nextInt();
printHandValue();
isWinner();
}

}

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 47

Expert Comment

by:for_yan
ID: 36544888
So you can use this method to draw cards - but you need to put it in class DeckOfCards
and then you need to create instance of this class and draw cards form it and aadd them to each of your hands
Try doing it - I'll then correct.

  public Card drawFromDeck()
	    {
	        Random generator = new Random();
	        int index= generator.nextInt( cards.size() );
	        return cards.remove(index);
	    }
	 

Open in new window

0
 

Author Comment

by:ryanbecker24
ID: 36545072
Is there another way besides creating a seperate method such as calling other methods?
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36545136
well, insetad of calling method you can put the code inside this method - but then you ned to do it
every time you draw a card or to have a loop - why not haveing such method - makes sense to jhave it
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36545399
Actually now that I pasted your code into my IDE I found some usweful methods in there. So we camnn make this method
0
 
LVL 47

Accepted Solution

by:
for_yan earned 2000 total points
ID: 36545455
Should be something like that:

So what s it that you don;t understand that you cannot do it yourself?

Exaoplain me what is it you don;t unsderatsn adfter all waht we went through - and
you should be able to do it yourself.

Also post your code between the code tags , like I am doing and
and sepatartely each public class - it will simplify even looking at it
public void twoPlayerBlackJack()
{
int size01,size02;
DeckOfCards myDeck = new DeckOfCards();
while(toContinue())
{
Random generator = new Random();
size01= generator.nextInt(8);
ArrayList<Card> hand1 = myDeck.getHand(size01+3);   
size02 = generator.nextInt(8);
    ArrayList<Card> hand2 = myDeck.getHand(size02+3);  
printHandValue(hand1);
printHandValue(hand2);    
System.out.println(isWinner(hand1, hand2));
}

}

Open in new window

0
 

Author Comment

by:ryanbecker24
ID: 36550043
Thank you for all your help.
0
 
LVL 47

Expert Comment

by:for_yan
ID: 36550049
You are always welcome.
0
 

Author Closing Comment

by:ryanbecker24
ID: 36550051
Thanks again
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question