Java Reference
In-Depth Information
return cardStr;
}
// Other members as before...
}
Here we just use two switch statements to sort out the strings to represent the face value and the suit
respectively from the values of the data members. In general, we might need to be able to compare
cards, so we could also implement the Comparable interface:
class Card implements Comparable {
// Compare two cards
public int compareTo(Object card) {
if(suit != ((Card)card).suit) // First compare suits
return suit < ((Card)card).suit ? -1: 1; // Sequence is C<D<H<S
else // Suits are the same
if(value == ((Card)card).value) // So check face values
return 0; // They are equal
else
return value < ((Card)card).value ? -1 : 1;
}
// Other members as before...
}
We could represent a hand of cards that is dealt from a deck as an object of type Hand . A Hand object
will need to be able to accommodate an arbitrary number of cards as this will depend on what game the
hand is intended for. We can define the Hand class using a Stack object to store the cards:
// Class defining a hand of cards
import java.util.*;
class Hand {
public void add(Card card) {
hand.push(card);
}
public String toString() {
Iterator cards = hand.iterator();
StringBuffer str = new StringBuffer();
while(cards.hasNext())
str.append(" "+ (Card)cards.next());
return str.toString();
}
private Stack hand = new Stack(); // Stores the cards in the hand
}
Search WWH ::




Custom Search