我试图解决Oracle-Java教程中的扑克牌练习:
public class CardClass {
public static String suit;
public static String rank;
final String[] suits = {"cloves","hearts","spades","diamonds"};
final String[] ranks = {"Ace","2","3","4","5","6","7","8","9","Jack","Queen","King"};
public CardClass(int suit, int rank) {
// TODO Auto-generated constructor stub
CardClass.suit = suits[suit];
CardClass.rank = ranks[rank];
}
public static void printCard() {
System.out.println("The card's suit is: " + suit + " and the card's rank is: " + rank);
}
public static void main(String[] args) {
new CardClass(1,1);
printCard();
}
}
和
public class DeckClass{
public static String[][] deck;
public DeckClass() {
// TODO Auto-generated constructor stub
for(int i=0; i<4;i++) {
for(int j=0; j<13; j++)
deck[i][j]= new CardClass(i,j);
}
}
public static void printDeck() {
for(String a: deck["hearts"]) {
System.out.println("In hearts the deck contains:"+ a);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new DeckClass();
printDeck();
}
}
我收到以下错误:
类型不匹配:无法从CardClass转换为String deck [i] [j] = new CardClass(i,j);
类型不匹配:无法从String转换为int in for(String a:deck [&#34; hearts&#34;]){
怎么办?我在这方面相当新手,只能选择某种西装来打印出二维阵列的卡片,所以我选择了心。
答案 0 :(得分:0)
在DeckClass的构造函数中,您尝试将CardClass类的实例分配给String数组。为了使代码有效,您需要将deck更改为CardClass数组。
对于printDeck方法,您无法使用String访问基本数组中的索引。您必须使用int值。例如,为了访问3个心(假设你的构造函数正在工作),我会使用:
final CardClass fourOfHearts = deck[1][3];
查看此doc的Array Access部分: https://docs.oracle.com/javase/specs/jls/se8/html/jls-10.html