MyRandom rnd = new MyRandom();
Card c1 = cards[rnd.nextInt(cards.length)-1];
Card c2 = cards[rnd.nextInt(cards.length)-1];
System.out.println("Two cards are drawn:");
System.out.println("c1 = " + c1 + " and c2 = " + c2);
// compare c1 and c2
if (c1.compareTo(c2) < 0) {
System.out.println(c1 + " is smaller than " + c2);
}
else if (c1.compareTo(c2) == 0) {
System.out.println(c1 + " is the same as " + c2);
}
else {
System.out.println(c1 + " is larger than " + c2);
}
}
}
这个compare to 应该怎么写?
public int compareTo(Card c) {
public class Card {
char cardNumber;
public Card(char chr) {
// TODO Auto-generated constructor stub
this.cardNumber = chr;
}
public int compareTo(Card c) {
int out = 0;
if ((byte) this.cardNumber < (byte) c.cardNumber) {
out = -1;
}
if ((byte) this.cardNumber > (byte) c.cardNumber) {
out = 1;
}
return out;
}
}
import java.util.Random;
public class MyRandom {
public int nextInt(int max) {
Random r = new Random();
return Math.abs(r.nextInt(max) % max + 1);
}
}
public class CardTest {
public static void main(String[] args) {
MyRandom rnd = new MyRandom();
Card[] cards = { new Card('1'), new Card('2') };
System.out.println(rnd.nextInt(cards.length) - 1);
Card c1 = cards[rnd.nextInt(cards.length) - 1];
Card c2 = cards[rnd.nextInt(cards.length) - 1];
System.out.println("Two cards are drawn:");
System.out.println("c1 = " + c1 + " and c2 = " + c2);
// compare c1 and c2
if (c1.compareTo(c2) < 0) {
System.out.println(c1 + " is smaller than " + c2);
} else if (c1.compareTo(c2) == 0) {
System.out.println(c1 + " is the same as " + c2);
} else {
System.out.println(c1 + " is larger than " + c2);
}
}
}