我正在制作与卡相关的应用程序。
花色分为梅花、方块、黑桃、红心
我想这样订购它们:
在牌中,Ace 是最高的,2 是最低的,所以标准的 Ace King Queen Jack 顺序就可以了。
我正在尝试使用 compareTo 方法。我完全不明白。
我是一个视觉学习者,所以代码示例,例如如何使用该方法的逐步演练会 - 真的 - 帮助我。它不必与我的代码相关,任何我可以通过视觉学习来学习和尝试实现的东西都会在这一点上有所帮助。
到目前为止,这是我的代码。如果有人可以告诉我 - 我应该在哪里实现这个,那也会有所帮助。
import java.util.Arrays;
public class PlayingCard implements Comparable {
// Class Constants
public static final int ACE = 1;
public static final int KING = 13;
public static final int QUEEN = 12;
public static final int JACK = 11;
public static final String SPADES = "spades";
public static final String CLUBS = "clubs";
public static final String HEARTS = "hearts";
public static final String DIAMONDS = "diamonds";
// Instance Variables
private int rank;
private String suit;
// Constructor
public PlayingCard () {
this.rank = PlayingCard.QUEEN;
this.suit = PlayingCard.SPADES;
}
public PlayingCard (int rank, String suit) {
this.rank = rank;
this.suit = suit;
Arrays.sort();
}
// Mutators
public void setRank (int rank) {
this.rank = rank;
}
public void setSuit (String suit) {
this.suit = suit;
}
// Accessors
public int getRank () {
return this.rank;
}
public String getSuit () {
return this.suit;
}
public String toString () {
return PlayingCard.rankToString(this.rank) + " of " + this.suit;
}
//Class Method
public static String rankToString(int rank) {
switch (rank) {
case(1): return "Ace";
case(2): return "two";
case(3): return "three";
case(4): return "four";
case(5): return "five";
case(6): return "six";
case(7): return "seven";
case(8): return "eight";
case(9): return "nine";
case(10): return "ten";
case(11): return "Jack";
case(12): return "Queen";
case(13): return "King";
}
return "INVALID";
}
public static void main(String [] args) {
// Generate an array of playing cards
PlayingCard [] deck = new PlayingCard[52];
String [] suits = {PlayingCard.CLUBS, PlayingCard.DIAMONDS, PlayingCard.SPADES, PlayingCard.HEARTS};
for(int i = 0; i < suits.length; i++) { // Run through each suit
for (int j = 0; j < 13; j++) { // Make each card
deck[i*13 + j] = new PlayingCard(j+1, suits[i]);
}
}
// Shuffle cards
for(int i = 0; i < deck.length; i++) {
int newPos = (int)(Math.random()*52);
PlayingCard temp = deck[i];
deck[i] = deck[newPos];
deck[newPos] = temp;
}
// Print out cards
System.out.println("Shuffled Deck");
for(int i = 0; i < deck.length; i++) {
System.out.println(deck[i]);
}
// Sort the deck
Arrays.sort(deck);
// Print out cards
System.out.println("\n\nSorted Deck");
for(int i = 0; i < deck.length; i++) {
System.out.println(deck[i]);
}
}
}