# blackjack.java



## teresa91198 (Apr 24, 2007)

who can help to do it ??? i don't know how to do, i am studying the java.


----------



## Chicon (Jul 29, 2004)

I've downloaded your file in attachment. It seems to be corrupted and therefore, I'm unable to extract it (I use WinRar). To make sure the problem was not related to a bad transfert, I've downloaded it again with not avail.


----------



## teresa91198 (Apr 24, 2007)

i tried to download the RAR file again, that's no problem in it. i am also extract it and see the text file.


----------



## teresa91198 (Apr 24, 2007)

if you cannot DL the file. try this link~~~THX http://download.yousendit.com/30088F4C50CD1B70


----------



## Chicon (Jul 29, 2004)

I've downloaded your file from the new link you posted and I still meet the same problem.
Here's the diagnostic I get from WinRar :



WinRAR : Diagnostic messages said:


> *
> ! C:\Documents and Settings\Joe\Bureau\Blackjack01.rar: Unknown method in TestHand.java
> ! a2-0607.doc: The file "a2-0607.doc" header is corrupt
> ! C:\Documents and Settings\Joe\Bureau\Blackjack01.rar: Unknown method in a2-0607.doc
> ...




What are you using to extract your archived files ?

I suggest you to post the content of your .java files in a new post of this current thread.


----------



## teresa91198 (Apr 24, 2007)

A Playing Card Game - Blackjack

In this assignment, we are going to model a deck of playing card using our Object-Oriented Programming language - Java. We will use the playing card classes we have modelled to simulate a famous card game - Blackjack.

In a typical card game, each player gets a hand of cards. The deck is shuffled and cards are dealt one at a time from the deck and added to the players' hands. The game is won or lost depending on the value (namely, ace, 2, 3, …, 10, jack, queen and king) and suit (♠ spades, ♥ hearts, ♦ diamonds and ♣ clubs) of the cards that a player receives. In some games, cards can be removed from a hand, and new cards can be added.

From the above description, we can find out some common reusable classes like Card, Hand, and Deck. Game is also considered as a good candidate of class but it will be specified on some particular game (with corresponding game rules), and in our case, it will be Blackjack. For this specific game, our Hand class is not enough to adapt all the needs for the game. Thus, we extend our Hand class and write a BlackjackHand subclass.

Card (15 marks)

A Card object needs int instance variables to represent its value and suit. We use int variables here to ease our task in writing program. The instance variables are initialized in the constructor, and should not be allowed to be changed from outside the class, and are in fact never changed after the initialization. Instance methods getSuit() and getValue() should be provided so that it will be possible to discover the suit and value from outside the class. To facilitate comparison of cards in some of the card game, we need to have a compare() method also. The value of the cards determines their order (A > K > Q > J > … > 3 > 2). If two cards have a same value, the suit determines the order ( >  > • > ). Finally, there should be an instance method toString() that returns a string with both the value and suit, such as "Heart Q", instead of returning the meaningless numeric value. You may also define some constants in your class for the value and suit to make your program more readable and sensible.

A template has been given to you for this class to ease your work.

Hints: 
	An instance variable can be declared final provided it is either given an initial value in its declaration or is initialized in every constructor in the class.

Attributes:	value (int)
suit (int)

Methods:	Card(int, int) - constructor, creates a card with the given value and suit
getValue() - get method of value (returns an int value)
getSuit() - get method of suit (returns an int value)
compare(Card) - compares an external card with this card. The method returns an int to represent the order. If this card is smaller than the external card, the method returns a negative integer. If this card is larger, the method returns a positive integer. If the two cards are exactly the same, 0 will be returned.
toString() - returns a String representing the card

Deck (18 marks)

When a deck of cards is first created, it contains 52 cards, stored in an array in some standard order. The Deck class will need a constructor to create a new deck. The constructor needs no parameters because any new deck is the same as any other. As stated above, it should create the array and put in the 52 cards one by one, probably using a for loop.

There will be an instance method called shuffle() that will rearrange the 52 cards into a random order. To shuffle the cards, you may randomly choose two cards and swap their positions. Of course, the process must repeat for a several time to make the deck looks like shuffled.

The dealCard() instance method will get the next card from the deck. This function will have a return type of Card, since the caller needs to know what card is being dealt. It has no parameters. The Card returned should be taken out of the deck and will not be used again until next shuffle. The method will throw a RuntimeException if there is no available card to be dealt.

Thus, the program could keep track of how many cards it has used. This can be done by using an instance variable cardsUsed and an instance method getCardsUsed() that returns the int value. (Well, the variable cardsUsed can also be used to determine which card to be dealt in the dealCard() method)

You should also include an instance method toString() that will return a String representation of you current Deck using the following format in 4 lines: [⌂ first_card ⌂ second_card ⌂ … ⌂ 51st_card ⌂ 52nd_card ⌂], where ⌂ represents a space.

A template has been given to you for this class to ease your work.

Attributes:	cards (Card[])
cardsUsed (int)

Methods:	Deck() - constructor, initialize the array and its array elements.
shuffle() - a void method which will rearrange the card order randomly.
dealCard() - deals a card from the deck, returns a Card object. Throws a RuntimeException if no card can be dealt.
getCardsUsed() - get method of cardsUsed, returns a int value
toString() - returns a String representing the deck (which has been done for you)

Hand (36 marks)

When a hand object is first created, it has no cards in it. So, the only thing the constructor needs to do is to create enough space to store the cards for a hand. You can use an array to implement it. Your constructor should have a parameter to setup the maximum number of cards you can hold in a hand.

An addCard() instance method will add a card to the hand. This method needs a parameter of type Card to specify which card is being added. You should take care of the special cases such as the hand is already full.

For the removeCard() method, a parameter is needed to specify which card to remove. We can either specify the card itself ("Remove the ace of spades"), or the card by its position in the hand ("Remove the third card in the hand"). Thus, we'll have two removeCard() instance methods, one with a parameter of type Card and one with a parameter of type int specifying the position of the card in the hand. In the latter case, you should return the card that have been removed in the process. You should also take care of the special cases such as the hand is already empty or the card specified is not in the hand. You also need to shift the elements in the array so that there will be no empty (null) elements in the middle of the array (see the example given at the end of the assignment document)

Apart from adding a card to your hand and removing a card from your hand, we may need to get one of the cards from the hand. We thus need an instance method getCard(). In this method, we give an int argument to indicate which card is needed and the method will then return a Card object representing the chosen card. The card will not be removed from the hand

We also need an instance method getCardCount() that returns the number of cards in the hand.

When we play cards, we would like to sort the cards in a hand. Thus, we provide instance method sort(). No parameter is needed and no value will be returned. The sorting methods can make use of the Card's compare() method and the bubble sort algorithm taught in the lecture.

After playing a game, we throw out all cards from the hand. This can be simulated by a clear() method which removes all cards from the Hand object.

You should also include an instance method toString() that will return a String representation of you current Hand using the following format: [first_card ⌂ second_card ⌂ … ⌂ last_card], where ⌂ represents a space.

You need to start from the scratch for this class.

Attributes:	cards (Card[])
cardCount (int)

Methods:	Hand(int) - constructor, initialize the Card array. The int parameter represents the maximum size of the Card array.
addCard(Card) - a void method which will add the Card object in the parameter to the Hand's array.
removeCard(int) - a method which will remove the i-th Card object (indicated by the int parameter) from the Hand's array. If there is no such object, returns null; otherwise return the removed Card object.
removeCard(Card) - a void method which will remove the Card object from the Hand's array. If there is no such object, throws a RuntimeException.
clear() - a void method which will remove all cards from the hand by setting all elements in the Card array to null.
getCard(int) - a method which will return the i-th Card object (indicated by the int parameter) in the Hand's array.
getCardCount() - get method of cardCount, returns a int value
sort() - a void method that sorts the hand in the descending order of value If the value of the cards is the same, the card with larger suit goes first.
toString() - returns a String representing the hand

BlackjackHand (7 marks)

A subclass of the Hand class that represents a hand of cards the game of Blackjack. In our Blackjack game, each hand can hold a maximum of five cards.

In addition, you will need an instance method getPoint() to calculate the points of your hand for the game of Blackjack. In a Blackjack game, a face card (Jack, Queen or King) is counted as 10 points and a number card is counted as its numeric value. The special card Ace can be counted as 1 or 11, depends on the total of the other cards in a hand. You should first count it as 1; and after all cards are counted, if you've got an Ace and your point is now lower than 11, add 10 to your point (i.e. count the Ace as 11).

It is a relatively easy class. You need to start from the scratch.

Methods: BlackjackHand() - constructor, calls the superclass constructor and set the maximum size of the array to five.
getPoint() - returns an int value representing the points on your hand.

BlackjackGame (24 marks)

After we have finished the work on the classes for the playing cards, we are now going to develop the game logic. In your BlackjackGame class, you need to write a main method to simulate the game flow (in a simplified way).

In your game, the computer will act as the dealer. The general objective in Blackjack is to get a hand of cards whose value is as close to 21 as possible, without going over. The game goes like this:

1.	At the beginning, create a new deck of cards and two Blackjack hands representing the dealer and the player.

2.	Start the game by shuffling the cards

3.	Ask if the user wants a new game. If yes, clear both hands.

4.	Reshuffle the deck if there are not enough cards. (less than 12)

5.	Skip the first two cards (dealt but not given to anyone).

6.	Then, two cards are dealt into Dealer's hand and Player's hand respectively.

7.	Check if the dealer's and player's hands have a value of 21 at this point. If both have a value of 21, the game ties. New hands are dealt.
If only dealer's hand has a value of 21, dealer wins. Similarly, if only player's hand has a value of 21, player wins. (We call this case a "Blackjack")

8.	Then, the user sees his own cards and sees one of the dealer's two cards. (In a casino, the dealer deals himself one card face up and one card face down. All the user's cards are dealt face up.)

9.	The user makes a decision whether to "Hit", which means to add another card to her hand, or to "Stand", which means to stop taking cards.

10.	If the user Hits, there is a possibility that the user will go over 21. In that case, the game is over and the user loses. If not, then the process continues. The user gets to decide again whether to Hit or Stand.

11.	If the user gets 5 cards or 21 points, the user is forced to stand.

12.	If the user stands, the game will turn to the dealer's turn to draw cards. The user should now see all the dealer's cards at this point.

13.	The dealer only follows rules, without any choice. The rule is that as long as the value of the dealer's hand is less than or equal to 16 and the number of cards is less than 5, the dealer Hits (that is, takes another card).

14.	Now, the winner can be determined: If the dealer has gone over 21, the user wins. Otherwise, whose total is greater wins the game. If both have the same total, the game ties.

15.	Go back to Step 3 to start a new game.

A template has been given to you for this part. Complete the programme according to the above steps and the instruction in the comment.

/*
An object of type Deck represents an ordinary deck of 52 playing cards.
The deck can be shuffled, and cards can be dealt from the deck.
*/

public class Deck {

// You should declare the following variables here:
// 1. An array of 52 Cards, representing the deck.
// 2. An int variable cardsUsed indicating how many cards
// have been dealt from the deck.

public Deck() {
// Create an unshuffled deck of cards and initialize cardsUsed

// Hints: try to use a nested for loop -
// one of the for loop counts the suit, another counts the value
// use another counter to count the index of the card creating (0-51)
}

public void shuffle() {
// Put all the used cards back into the deck, and shuffle it into
// a random order. Reset the cardsUsed to zero.

// Hints:
// Method 1: try to use a for loop (e.g. 100 iteration),
// choose 2 random number between 0 and 51
// and swap the two cards in each iteration.
// Method 2: loop for 51 times and swap the current card
// with a random card
}

public int getCardsUsed() {
// As cards are dealt from the deck, the number of cards left
// decreases. This function returns the number of cards that
// are still left in the deck.
}

public Card dealCard() {
// Deals one card from the deck and returns it.
// The card should be the first unused card.
// Hints: use the variable cardsUsed and return the array element
// You need to throw a RuntimeException if no card is left:
// throw new RuntimeException("No card left");
}

public String toString() { // toString method is done for you.
String value = "[ ";
for (int i=0; i<deck.length; i++) {
value += deck_+" ";
if(i%13==12 && i!=deck.length-1) value+="\n";
}
return value + "]";
}

} // end class Deck

/*
This program lets the user play Blackjack.
The computer acts as the dealer.
The user can leave at any time.
House rules: The dealer hits on a total of 16 or less
and stands on a total of 17 or more.
A new deck of cards is used if less than 12 cards left.
*/

import javax.swing.JOptionPane;

public class BlackjackGame {

// for simplfying the input process
private static char input (String prompt) {
String input = "";
String message = prompt;
do {
input = JOptionPane.showInputDialog(message);
message = "Invalid Input!! \n" + prompt;
} while (input.length()!=1);
return input.charAt(0);
}

// for simplfying the output process
private static void output (String prompt) {
JOptionPane.showMessageDialog(null, prompt);
}

public static void main(String[] args) {

// variable initialization
int win = 0; // Number of wins
int lose = 0; // Number of loses
int tie = 0; // Numer of ties
String message; // Output Message OR input prompt

// STEP 1
// Create a deck of cards.
// Create dealer's blackjack hand
// Create player's blackjack hand
Deck deck;
BlackjackHand dealer, player;

// START THE GAME
// STEP 2
// shuffle the deck

// HERE IS THE GAME LOOP
while (true) { // continue to play until System.exit(0);

// STEP 3
// Ask if user is interested in playing another game
// (Done for you)

char ans; // store the user's reply
do {

ans = input("Do you want to deal a new game? (Y/N)");
if (ans=='N') {

// print end game stats
message = "Your game stat: " + win + " Win(s), "
+ lose + " Lose(s) and " + tie + " Tie(s).";
message += "\n" + "Thanks for play the blackjack game.";
output(message);

System.exit(0); // quit the game
}
if (ans!='Y') output("Please answer Y/N.");
} while (ans!='Y'); // loop until valid answer is obtained

// clear the hands before playing a new game
dealer.clear();
player.clear();

// STEP 4
// re-shuffle if there is not enough cards

// STEP 5
// Skip two cards (Done for you)
deck.dealCard();	// skip one card
deck.dealCard();	// skip two cards

// STEP 6
// Deal two cards to dealer and then two cards to player

/*
STEP 7
Check if player/dealer gets a Blackjack (two cards totaling to 21).
The one who gets a Blackjack wins the game.
If both get Blackjack, the game is tied.
You need to output a message stating the dealer's and player's point
and who wins (or ties) the game.
*/

if (dealer.getPoint() == 21 || player.getPoint() == 21) {
// *** ADD YOUR CODE HERE!!!
// Remember to update the number of win/lose/tie
output(message); // output the message
continue; // jump back to the beggining of game, skip the card draw part
}

/*
STEPS 8 - 12

If neither player nor dealer gets a Blackjack, play the game.
First the player gets a chance to draw cards (i.e., to "Hit").
The while loop ends when the player chooses to "Stand".
If the player goes over 21, the user loses immediately.
*/

while (true) { // player draw card loop

// STEPS 8, 9
// Card is shown to player
// Player decide to hit or stand
// (Done for you)

/* Display user's cards, and let user decide to Hit or Stand. */
message = "Dealer is showing the " + dealer.getCard(0);
message += "\n" + "Your cards are: " + player;
message += "\n" + "Your total is " + player.getPoint();
message += "\n\n" + "Hit (H) or Stand (S)? ";

// User's response, 'H' or 'S'.
char userAction;
do {
userAction = input(message);
if (userAction != 'H' && userAction != 'S')
output("Please respond H or S: ");
} while (userAction != 'H' && userAction != 'S');

/*
STEP 9
If the user Hits, the user gets a card. If the user Stands,
the loop ends (and it's the dealer's turn to draw cards).
*/

if ( userAction == 'S' ) break; // Loop ends; user is done taking cards.
else {
// userAction is 'H'. Give the user a card.
// *** ADD CODE HERE

// show the result of card drawing
output(message);

// STEP 10
// Check if player gets more than 21 points
// If yes, show message and break the loop.
// Remember to update the number of lose.

// STEP 11
// break the drawing loop when player gets 21 point or 5 cards
// (DONE FOR YOU)
if (player.getPoint() == 21) break;
if (player.getCardCount() == 5) {
output("You have got a maximum of 5 cards.");
break;
}
}
} // end card drawing loop

// If player gets busted, dealer needs not to draw card
// We should start a new game ==> Jump back to the top of the game loop
if (player.getPoint() > 21) continue;

/*
STEPS 12 - 14
If we get to this point, the user has Stood with 21 or less. Now, it's
the dealer's chance to draw. Dealer draws cards until the dealer's
total is > 16. If dealer goes over 21, the dealer loses.
*/

// STEP 12
// Show Dealer's hand
// (Done for you)

message = "User stands.";
message += "\n" + "Dealer's cards are: " + dealer;
output (message);

// STEP 13
// Dealer's drawing loop
// Keep on drawing if dealer has less than or equal to 16 points
// and the number of cards is less than 5

while (/*** FILL IN THE CONDITION HERE ***/) {
// Deal a card
// show the card drawn by using output(...)
// add the drawn card to dealer's hand
}

// STEP 14
// Check if dealer gets more than 21 points (busted)
// If yes, show the winning message and remember to update the win number
// *** ADD YOUR CODE HERE

/*
STEP 14 (cont'd)
If we get to this point, both players have 21 or less. We
can determine the winner by comparing the points of their hands.
Output the win/lost/tie message. Remember to update the win/lose/tie number
*/
// *** ADD YOUR CODE HERE
} // end game loop

} // end main()

} // end class Blackjack_


----------



## Chicon (Jul 29, 2004)

First, I suggest you to proceed class by class in the strict order defined by the analyze. Then, I will eventually have a look on them. We will treat the steps of the main application lately. 
I've started to build the Card class accordingly to the analyze requirements.


```
[SIZE=2]
public class Card {
// Attributes required
    private int value;
    private int suit;
// Attributes defined at development
    private final String[] VALUE = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
    private final String[] SUIT = {"Spade", "Heart", "Diamond", "Club"};
    
// Contructor required    
    public Card(int value, int suit) {
        this.value = value;
        this.suit = suit;
    }
// Methods required
    public int getValue() {
        return this.value;
    }
    
    public int getSuit() {
        return this.suit;
    }
    
    public String toString() {
        String v = this.VALUE[this.value];
        String s = this.SUIT[this.suit];
        return s + " " + v;
    }
    
    public int compare(Card card) {
        int value = card.getValue();
        int suit = card.getSuit();
        if (value==this.value) {
            if (suit==this.suit) {
                return 0;
            } else {
                if (suit < this.suit) {
                    return 1;
                } else {
                    return -1;
                }
            }
        } else {
            if (value < this.value) {
                return 1;
            } else {
                return -1;
            }
        }
    }
}

[/SIZE]
```


----------



## teresa91198 (Apr 24, 2007)

i did it today, it is different your card class.~~

/*
An object of class card represents one of the 52 cards in a
standard deck of playing cards. Each card has a suit and
a value.
*/

public class Card {

private static final String[] SUIT = { "Club", "Diamond", "Heart", "Spade" };
private static final String[] VALUE = {
"0", "0", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "J", "Q", "K", "A"};

public final static int SPADES = 3, // Codes for the 4 suits.
HEARTS = 2,
DIAMONDS = 1,
CLUBS = 0;

public final static int ACE = 14, // Codes for non-numeric cards.
JACK = 11, // Cards 2 through 10 have
QUEEN = 12, // their numerical values
KING = 13; // for their codes.

private final int suit; // The suit of this card, one of the
// four constants: SPADES, HEARTS,
// DIAMONDS, CLUBS.

private final int value; // The value of this card, from 2 to 14.
// Ace is 14 because it is the largest card.

public Card(int theValue, int theSuit) {
// Construct a card with the specified value and suit.
// Value must be between 2 and 14. Suit must be between
// 0 and 3. If the parameters are outside these ranges,
// the constructed card object will be invalid.

if(2<=theValue && theValue<=ACE)
value = theValue;
else
throw new IllegalArgumentException("Invalid value: " + theValue);

if(CLUBS<=theSuit && theSuit<=SPADES)
suit = theSuit;
else
throw new IllegalArgumentException("Invalid suit: " + theSuit);
}

public int getSuit() {
// Return the int that codes for this card's suit.
return suit;
}

public int getValue() {
// Return the int that codes for this card's value.
return value;
}

public int compare(Card c) {
// Return 0 if c's suit and value
// is exact the same as the suit and value above.
if(suit==c.getSuit() && value==c.getValue())
return 0;

// If c has the same value as this card,
// return suit - c's suit
if(value==c.getValue())
return suit - c.getSuit();

// Otherwise, return value - c's value
else
return value - c.getValue();
}

public String toString() {
// Return a String representation of this card, such as
return SUIT[getSuit()] + " " + VALUE[getValue()];
}

} // end class Card


----------



## Chicon (Jul 29, 2004)

You're right, I made a mistake on this line :

*private final String[] VALUE = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};*

It must be :

*private final String[] VALUE = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};*

BTW, I have some remarks and questions :

- why the zeroes in the following line ? IMO, they are useless for the logic.
* private static final String[] VALUE = { "0", "0", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};*

- the following lines are redundant :
* public final static int SPADES = 3, // Codes for the 4 suits.
HEARTS = 2,
DIAMONDS = 1,
CLUBS = 0;*
with the informations contained in the following statement:
* private static final String[] SUIT = { "Club", "Diamond", "Heart", "Spade" };*

- the following lines are redundant :
* public final static int ACE = 14, // Codes for non-numeric cards.
JACK = 11, // Cards 2 through 10 have
QUEEN = 12, // their numerical values
KING = 13; // for their codes.*
with the informations contained in the following statement :
* private static final String[] VALUE = {"0", "0", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};*

- why are you throwing an IllegalArgumentException ? It is not required in the analyze you posted.

- where did you get the order of the suits you coded ? The only reference I find in the analyze is *... and suit (♠ spades, ♥ hearts, ♦ diamonds and ♣ clubs) ...*.

- also, why the word *static* in the declaration of constants ? It's useless as the constants are not used outside the class (*private*). The word *final* is sufficient as a constant may not be modified.

BTW, you gave me an idea :


```
[SIZE=2]
public class Card {
// Attributes required
    private int value;
    private int suit;
// Attributes defined at development
    private final String[] VALUE = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
    private final String[] SUIT = {"Spade", "Heart", "Diamond", "Club"};
    
// Contructor required    
    public Card(int value, int suit) {
        this.value = value;
        this.suit = suit;
    }
// Methods required
    public int getValue() {
        return this.value;
    }
    
    public int getSuit() {
        return this.suit;
    }
    
    public String toString() {
        String v = this.VALUE[this.value];
        String s = this.SUIT[this.suit];
        return s + " " + v;
    }
    
    public int compare(Card card) {
        int value = card.getValue();
        int suit = card.getSuit();
        if (value==this.value) {
            return this.suit - suit;
        } else {
            return this.value - value;
        }
    }
}
[/SIZE]
```


----------



## teresa91198 (Apr 24, 2007)

i try your code and my code, the three card class also can used by the testcard. but i don't know how to write the hand class. 

class TestCard {
public static void main (String args[]) {

// This part tests the constructor
Card c[] = {
new Card(14, 3),	// Spade A
new Card(14, 2),	// Heart A
new Card(11, 0),	// Club J
new Card(3, 1), // Diamond 3
new Card(11, 0) // Club J
};

// This part tests toString method
System.out.println("Card 0 (should print Spade A): " + c[0]);
System.out.println("Card 1 (should print Heart A): " + c[1]);
System.out.println("Card 2 (should print Club J): " + c[2]);
System.out.println("Card 3 (should print Diamond 3): " + c[3]);
System.out.println();

// This part tests getValue and getSuit
System.out.println("Card 0 have the value of (should be 14): " + c[0].getValue());
System.out.println("Card 0 have the suit of (should be 3): " + c[0].getSuit());
System.out.println("Card 3 have the value of (should be 3: " + c[3].getValue());
System.out.println("Card 3 have the suit of (should be 1): " + c[3].getSuit());
System.out.println();

// This part tests compare method
System.out.println("Card 1 should be larger than Card 2 (return +ve int): " +
c[1].compare(c[2]));
System.out.println("Card 1 should be smaller than Card 0 (return -ve int): " +
c[1].compare(c[0]));
System.out.println("Card 2 should be larger than Card 4 (return 0): " +
c[2].compare(c[4]));

}
}


----------



## Chicon (Jul 29, 2004)

Here's an example of coding of the Hand class :


```
[SIZE=2]
public class Hand {
// Attributes required
    private Card[] cards;
    private int cardCount;

// Constructor required    
    public Hand(int parameter) {
        this.cards = new Card[parameter];
    }
    
// Methods requireds
    public void addCard(Card card) {
        if (this.cardCount < this.cards.length) {
            this.cards[this.cardCount] = card;
            this.cardCount++;
        }
    }
    
    public Card removeCard(int position) {
// position of the first item in the array = 1
        int index = position - 1;
        if (this.cards[index] == null) {
            return null;
        } else {
            Card c = this.cards[index];
            this.shiftArray(position);
            this.cardCount--; 
            return c;
        }
    }
    
    public void removeCard(Card c) throws RuntimeException {
        boolean isFound = false;
        int index = 0;
        while ( !(isFound) && !(index == this.cardCount)) {
            if (c == this.cards[index]) {
                isFound = true;
            } else {
                index++;
            }
        }
        if (isFound) {
            this.shiftArray(index+1);
            this.cardCount--;
        } else {
            throw new RuntimeException();
        }
    }
    
    public void clear() {
        for (int i = 0; i < this.cardCount; i++) {
            this.cards[i] = null;
        }
        this.cardCount = 0;
    }
    
    public Card getCard(int position) {
// position of the first item in the array = 1
        int index = position -1;
        return this.cards[index];
    }
    
    public int getCardCount() {
        return this.cardCount;
    }
    
    public void sort() {
        if (this.cardCount > 1) {
            for (int i = 0; i < (this.cardCount - 1); i++) {
                for (int j = 0; j < (this.cardCount - 1 - i); j++) {
                    Card a = this.cards[j];
                    Card b = this.cards[j+1];
                    if (a.compare(b) < 0) {
                        this.cards[j] = b;
                        this.cards[j+1] = a;
                    }
                }
            }
        }
// Comment : - in the first iteration of i, the 'smallest' card will be moved
// to the last position
//           - in the second iteration of i, the 'smallest' from the remaining cards
// will be moved to the last position - 1
// and so on        
    }
    
    public String toString() {
        if (this.cardCount > 0) {
            String result = "";
            for (int i = 0; i < this.cardCount; i++) {
                result = result + this.cards[i].toString() + " ";
            }
            return result.trim(); // remove the trailing space
        } else {
            return null;
        }
    }

// Methods implemented at development
    
// The following method is used by both removeCard methods    
    private void shiftArray(int position) {
// position of the first item in the array = 1
        for (int i = (position-1); i < (this.cardCount-1); i++) {
            this.cards[i] = this.cards[i+1];
        }
        this.cards[this.cardCount-1] = null;
    }
}
[/SIZE]
```
If you have some questions, please feel free to ask.


----------



## teresa91198 (Apr 24, 2007)

i saw your code of hand class, it helps me to learn the Constructor more and clearly. i just understand how to write the Constructor. THANK YOU ^^
if i want to play the blackjack, how to combine the all of class, for example: Card, Deck, Hand, BlackjackHand, Blackjack (Game).

/*
This program lets the user play Blackjack.
The computer acts as the dealer.
The user can leave at any time.
House rules: The dealer hits on a total of 16 or less
and stands on a total of 17 or more.
A new deck of cards is used if less than 12 cards left.
*/

import javax.swing.JOptionPane;

public class BlackjackGame {

// for simplfying the input process
private static char input (String prompt) {
String input = "";
String message = prompt;
do {
input = JOptionPane.showInputDialog(message);
message = "Invalid Input!! \n" + prompt;
} while (input.length()!=1);
return input.charAt(0);
}

// for simplfying the output process
private static void output (String prompt) {
JOptionPane.showMessageDialog(null, prompt);
}

public static void main(String[] args) {

// variable initialization
int win = 0; // Number of wins
int lose = 0; // Number of loses
int tie = 0; // Numer of ties
String message; // Output Message OR input prompt

// STEP 1
// Create a deck of cards.
// Create dealer's blackjack hand
// Create player's blackjack hand
Deck deck;
BlackjackHand dealer, player;

// START THE GAME
// STEP 2
// shuffle the deck

// HERE IS THE GAME LOOP
while (true) { // continue to play until System.exit(0);

// STEP 3
// Ask if user is interested in playing another game
// (Done for you)

char ans; // store the user's reply
do {

ans = input("Do you want to deal a new game? (Y/N)");
if (ans=='N') {

// print end game stats
message = "Your game stat: " + win + " Win(s), "
+ lose + " Lose(s) and " + tie + " Tie(s).";
message += "\n" + "Thanks for play the blackjack game.";
output(message);

System.exit(0); // quit the game
}
if (ans!='Y') output("Please answer Y/N.");
} while (ans!='Y'); // loop until valid answer is obtained

// clear the hands before playing a new game
dealer.clear();
player.clear();

// STEP 4
// re-shuffle if there is not enough cards

// STEP 5
// Skip two cards (Done for you)
deck.dealCard();	// skip one card
deck.dealCard();	// skip two cards

// STEP 6
// Deal two cards to dealer and then two cards to player

/*
STEP 7
Check if player/dealer gets a Blackjack (two cards totaling to 21).
The one who gets a Blackjack wins the game.
If both get Blackjack, the game is tied.
You need to output a message stating the dealer's and player's point
and who wins (or ties) the game.
*/

if (dealer.getPoint() == 21 || player.getPoint() == 21) {
// *** ADD YOUR CODE HERE!!!
// Remember to update the number of win/lose/tie
output(message); // output the message
continue; // jump back to the beggining of game, skip the card draw part
}

/*
STEPS 8 - 12

If neither player nor dealer gets a Blackjack, play the game.
First the player gets a chance to draw cards (i.e., to "Hit").
The while loop ends when the player chooses to "Stand".
If the player goes over 21, the user loses immediately.
*/

while (true) { // player draw card loop

// STEPS 8, 9
// Card is shown to player
// Player decide to hit or stand
// (Done for you)

/* Display user's cards, and let user decide to Hit or Stand. */
message = "Dealer is showing the " + dealer.getCard(0);
message += "\n" + "Your cards are: " + player;
message += "\n" + "Your total is " + player.getPoint();
message += "\n\n" + "Hit (H) or Stand (S)? ";

// User's response, 'H' or 'S'.
char userAction;
do {
userAction = input(message);
if (userAction != 'H' && userAction != 'S')
output("Please respond H or S: ");
} while (userAction != 'H' && userAction != 'S');

/*
STEP 9
If the user Hits, the user gets a card. If the user Stands,
the loop ends (and it's the dealer's turn to draw cards).
*/

if ( userAction == 'S' ) break; // Loop ends; user is done taking cards.
else {
// userAction is 'H'. Give the user a card.
// *** ADD CODE HERE

// show the result of card drawing
output(message);

// STEP 10
// Check if player gets more than 21 points
// If yes, show message and break the loop.
// Remember to update the number of lose.

// STEP 11
// break the drawing loop when player gets 21 point or 5 cards
// (DONE FOR YOU)
if (player.getPoint() == 21) break;
if (player.getCardCount() == 5) {
output("You have got a maximum of 5 cards.");
break;
}
}
} // end card drawing loop

// If player gets busted, dealer needs not to draw card
// We should start a new game ==> Jump back to the top of the game loop
if (player.getPoint() > 21) continue;

/*
STEPS 12 - 14
If we get to this point, the user has Stood with 21 or less. Now, it's
the dealer's chance to draw. Dealer draws cards until the dealer's
total is > 16. If dealer goes over 21, the dealer loses.
*/

// STEP 12
// Show Dealer's hand
// (Done for you)

message = "User stands.";
message += "\n" + "Dealer's cards are: " + dealer;
output (message);

// STEP 13
// Dealer's drawing loop
// Keep on drawing if dealer has less than or equal to 16 points
// and the number of cards is less than 5

while (/*** FILL IN THE CONDITION HERE ***/) {
// Deal a card
// show the card drawn by using output(...)
// add the drawn card to dealer's hand
}

// STEP 14
// Check if dealer gets more than 21 points (busted)
// If yes, show the winning message and remember to update the win number
// *** ADD YOUR CODE HERE

/*
STEP 14 (cont'd)
If we get to this point, both players have 21 or less. We
can determine the winner by comparing the points of their hands.
Output the win/lost/tie message. Remember to update the win/lose/tie number
*/
// *** ADD YOUR CODE HERE
} // end game loop

} // end main()

} // end class Blackjack


----------



## Chicon (Jul 29, 2004)

teresa91198 said:


> ...
> if i want to play the blackjack, how to combine the all of class, for example: Card, Deck, Hand, BlackjackHand, Blackjack (Game).


When all your classes Card, Deck, Hand, BlackjackHand are built and tested, just proceed step by step in the template of the Blackjack.

Example for STEP 1



> // STEP 1
> // Create a deck of cards.
> // Create dealer's blackjack hand
> // Create player's blackjack hand
> ...




```
[SIZE=2]
// STEP 1
// Create a deck of cards.
// Create dealer's blackjack hand
// Create player's blackjack hand
Deck deck = new Deck();
BlackjackHand dealer = new BlackjackHand(); 
BlackjackHand player = new BlackjackHand();
// Comment :
// as BlackjackHand is an extension of the Hand class, both dealer and player will inherit
// the attributes and the methods of the Hand class. Also, each of them will have their inherited
cards array attribute set to a length of 5 items.
[/SIZE]
```
Edit : Here's my BlackjackHand class :


```
[SIZE=2]
public class BlackjackHand extends Hand {
    
// Constructor required 
    public BlackjackHand() {
        super(5);
    }
    
// Methods required
    public int getPoint() {
        if (this.getCardCount() == 0) {
            return 0;
        } else {
            int result = 0;
            int numberAces = 0;
            for (int i = 0; i < this.getCardCount(); i++) {
                Card card = this.getCard(i+1);
                int value = card.getValue();
                if (value < 9) {
                    result = result + value + 2;
                } else {
                    if (value < 12) {
                        result = result + 10;
                    } else {
                        result++;
                        numberAces++;
                    }
                }
            }
            while (numberAces > 0) {
                if (result < 11) {
                    result = result + 10;
                }
                numberAces--;
            }
            return result;
        }
    }
}
[/SIZE]
```


----------



## Chicon (Jul 29, 2004)

teresa91198 said:


> ...
> if i want to play the blackjack, how to combine the all of class, for example: Card, Deck, Hand, BlackjackHand, Blackjack (Game).


Oops, I've just noticed that I didn't answer your question as I had another idea in my mind. 

I don't know what IDE you're using to develop Java applications but most of them have a tool to generate a .jar file.
Normally, if your system is well configured, you can launch your application via a .jar file you still have to build.

What's a .jar file ?
It's a kind of archive file that contains compiled classes and other ressources needed by the application.

How to build a .jar file ? (detailed explanations here)
First, all the classes of your application must be compiled and your .class files must be stored in the same directory.
If you browse the *bin* directory of your *JDK*, you'll notice there's an executable file called *jar.exe*.
Therefore, you can build your own .jar in a DOS window. When you type *jar ?*, you'll have a description of the command
with a list of options.
Also, as your application contains many classes, you have to create a file called the Manifest. It is a special file that must be inserted in the .jar file.
The Manifest is used to notify to the JVM which class must be launched first at the start and eventually the path of the third-party libraries needed by the application.

How to run a .jar file ?
You've just to double click on the icon of your .jar file to launch your game.


----------



## teresa91198 (Apr 24, 2007)

I finished the all class, it works and can played. thank you your help. i am very happy i can recognize you^^.THANKS i want to ask you. i learn the java for one months, how to learn it more better and improve my programming knowledge .


----------



## Chicon (Jul 29, 2004)

teresa91198 said:


> I finished the all class, it works and can played. thank you your help. i am very happy i can recognize you^^.THANKS i want to ask you. i learn the java for one months, how to learn it more better and improve my programming knowledge .


:up: 
You're welcome ! 

If you want to improve your knowledge, the better way is to build your own programs for yourself. Also, I suggest you to have some try with Java Swing, multi-threading and multi-tasking.


----------



## Rosicky (May 7, 2007)

teresa91198 said:


> I finished the all class, it works and can played. thank you your help. i am very happy i can recognize you^^.THANKS i want to ask you. i learn the java for one months, how to learn it more better and improve my programming knowledge .


can you share whole file of this ?
I want to play this blackjack.java


----------



## johnny1125 (May 15, 2007)

Rosicky said:


> can you share whole file of this ?
> I want to play this blackjack.java


收啦你,張雲滴!!!!!!!!!
41304 2b


----------

