1.來源:java8技術手冊
2.問題描述:
當運行程式時,結果為下列程式碼,程式該如何修改才能得到字串形式的結果?
My hand is CardGame.Card@6d06d69c CardGame.Card@7852e922 CardGame.Card@4e25154f CardGame.Card@70dea4e CardGame.Card@5c647e05+
Your hand is CardGame.Card@33909752 CardGame.Card@55f96302 CardGame.Card@3d4eac69 CardGame.Card@42a57993 CardGame.Card@75b84c92+
3. ** 附上6段程式碼**
3-1.
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES
}
3-2.public enum Rank { TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE }
3-3.
public class Card implements Comparable<Card>{
private Suit suit;
private Rank rank;
public Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
@Override
public int compareTo(Card card) {
if(suit.equals(card.suit)) {
if(rank.equals(card.rank)) {
return 0;
}
return rank.compareTo(card.rank)<0 ? -1 : 1;
}else {
return suit.compareTo(card.suit)<0 ? -1 : 1;
}
}
public String toSring() {
return rank + " of " + suit; }
}
3-4.
public class Hand {
private Vector<Card> hand = new Vector<Card>();
public void add(Card card) {
hand.add(card);
}
public Hand sort() {
Collections.sort(hand);
return this;
}
public String toString() {
StringBuilder str = new StringBuilder();
for(Card card : hand) {
str.append(" " +card);
}
return str.toString();
}
}
3-5.
public class CardDeck {
public CardDeck() {
for(Suit suit : Suit.values())
for(Rank rank : Rank.values())
deck.push(new Card(rank, suit));
}
public Hand dealHand(int numCards) {
Hand hand = new Hand();
for(int i = 0; i<numCards; i++) {
hand.add((Card)deck.pop());
}
return hand;
}
public void shuffle() {
Collections.shuffle(deck);
}
private Stack<Card> deck = new Stack<Card>();
}
3-6.
class TryDeal {
public static void main(String[] args) {
CardDeck deck = new CardDeck();
deck.shuffle();
Hand myHand = deck.dealHand(5).sort();
Hand yourHand = deck.dealHand(5).sort();
System.out.println("\nMy hand is" + myHand);
System.out.println("\nYour hand is" + yourHand);
}
}
class Card 的 toString 方法少個t?
你好棒喔,愛你
還有 是不是發錯版了.
我下次注意一下