我写了这个代码,随机从一副牌中挑选两张牌,但是我在尝试比较它时遇到了麻烦,我遇到了一些问题,想要一步一步地解决这个问题,但不确定如何比较这两个语句只有一个定义的变量?
package question1;
public class HouseOfCards {
public static void main(String[] args) {
String [] SuitNames= {
"Spades","Diamonds","Clubs","Hearts"
};
String [] CardNames= {
"Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"
};
String SuitName="hi",SuitName2="die";
String CardName="hi", CardName2="die";
for (int i=0; i<=1; i++){
int numCard=52;
int randNum=(int)(Math.random() * numCard);
int randNum2=(int)(Math.random() * numCard);
int suitNum = randNum / 13;
int cardNum = randNum % 13;
int suitNum2 = randNum2 / 13;
int cardNum2 = randNum2 % 13;
SuitName = SuitNames[suitNum];
CardName = CardNames[cardNum];
SuitName2 = SuitNames [suitNum2];
CardName2 = CardNames[cardNum2];
System.out.println(CardName + " of " + SuitName);
}
if (CardName.equals(CardName2)){
System.out.println("Same Rank");
}
else if (SuitName.equals(SuitName2)){
System.out.println("Same Suit");
}
}
}
我编辑了我的代码,以便显示它是否在随机选择的卡片之间的相同等级或随机选择的卡片之间的相同套装,但有时它不打印声明,为什么?
答案 0 :(得分:0)
尝试这样的事情:
public class HouseOfCards {
public class HouseOfCards {
public static void main(String[] args) {
int Spades=1;
String [] suitNames= {
"Spades","Diamonds","Clubs","Hearts"
};
String [] cardNames= {
"Ace","One","Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King"
};
String card1="";
String card2="";
String suitName="";
String cardName1="";
String suitName2="";
String cardName2="";
int cardPosition1 = 0;
int cardPosition2 = 0;
for (int i=0; i<=1; i++){
int numCard=52;
int randNum=(int)(Math.random() * numCard);
int suitNum = randNum / 13;
int cardNum = randNum % 13;
if(i==0) {
suitName = suitNames[suitNum];
cardName1 = cardNames[cardNum];
card1 = cardName1+" of "+suitName;
}
else {
suitName2 = suitNames[suitNum];
cardName2 = cardNames[cardNum];
card2 = cardName2+" of "+suitName2;
}
}
System.out.println(card1);
System.out.println(card2);
for (int i = 0; i < cardNames.length; i++) {
if(cardName1.equals(cardNames[i])) {
cardPosition1 = i;
}
if(cardName2.equals(cardNames[i])) {
cardPosition2 = i;
}
}
System.out.println(cardPosition1);
System.out.println(cardPosition2);
if(cardPosition1>cardPosition2) {
System.out.println("First card has bigger number");
}
else if (cardPosition1<cardPosition2) {
System.out.println("Second card has bigger number");
}
else if (cardPosition1==cardPosition2) {
System.out.println("Equal cards (probably different suites you can check it further)");
}
}
}