【发布时间】:2020-08-20 20:33:51
【问题描述】:
为此,我创建了两个 java 文件。 Card.java 具有所有实例变量,Jack.java 会在被询问时运行所有card。
我的 Card.java 代码是:
public class Card {
private int rank;
private int suit;
public Card(int rank, int suit) {
this.rank = rank;
this.suit = suit;
}
public static final String[] RANKS = {
null, "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King"};
public static final String[] SUITS = {
"Clubs", "Diamonds", "Hearts", "Spades"};
public String toString() {
String s = RANKS[this.rank] + " of " + SUITS[this.suit]; // we are actually using the instances variables to access the array elements
return s;
}
public boolean equals(Card that) { // this that could be any variables
return this.rank == that.rank && this.suit == that.suit;
}
}
我的 Jack.java 代码是:
public class Jack {
public static void main(String[] args) {
Card small = new Card(0,1); // creates the small object
Card card = new Card(11,1); // cretes the card object
System.out.println(small); // prints the small class
System.out.println(card); // prints the card class
System.out.println(small.equals(card)); // compares small with cards
Card[] cards = new Card[52];
int index = 0; // to keep track
for (int suit = 0; suit <= 3; suit++) { // outer loop
for (int rank = 1; rank <= 13; rank++) { // inner loop
cards[index] = new Card(rank, suit);
index++;
}
}
public static void printDeck(Card[] cards) {
for (Card card : cards) {
System.out.println(card);
}
}
System.out.println(Arrays.toString(cards));
}
}
所有代码都有效,但 PrintArray 无效。我试图从书中获得帮助,但我没有得到可能的错误。提前致谢。我还尝试将 void 方法 printDeck 放在 Card.java 文件中,但又失败了。
【问题讨论】:
-
当你说它不起作用时 - 为什么?你能详细解释一下这个问题吗?
-
代码无效 - 如果你愿意,你可以在代码级别有一个方法
printDeck- 它需要是一个类级别的项目。
标签: java class variables instance