我有一个程序,根据随机数的值处理20张卡片。到目前为止,它可以处理诸如黑桃王、红心牌等卡片。我的工作是用一种方法检查这些卡片是否是重复的,但没有数组。下面是我检查副本的解决方案,但由于明显的原因,它不起作用:
public class Driver {
public static void main(String [] args) {
for (int i = 0; i < 20; i++){
Cards card1 = new Cards();
Cards card2 = card1;
if (card1 == card2) {
card1 = new Cards();
}
System.out.println(card1);
}
}
}这是我的支持课:
import java.util.Random;
public class Cards {
String hearts = "Hearts";
String diamonds = "Diamonds";
String clubs = "Clubs";
String spades = "Spades";
String suit;
int cardNumber;
String numberName;
String suitName;
Random randomNum = new Random();
public Cards () {
}
public String suit() {
int theRandom = randomNum.nextInt(4);
if (theRandom == 0 ) {
suitName = "hearts";
}
else if ( theRandom == 1) {
suitName = "diamonds";
}
else if (theRandom == 2) {
suitName = "clubs";
}
else {
suitName = "spades";
}
return suitName;
}
public String number() {
int theRandomNum = randomNum.nextInt(12 + 1);
if ( theRandomNum == 1 ) {
numberName = "Ace";
}
else if ( theRandomNum == 2) {
numberName = "2";
}
else if ( theRandomNum == 3) {
numberName = "3";
}
else if ( theRandomNum == 4) {
numberName = "4";
}
else if ( theRandomNum == 5) {
numberName = "5";
}
else if ( theRandomNum == 6) {
numberName = "6";
}
else if ( theRandomNum == 7) {
numberName = "7";
}
else if ( theRandomNum == 8) {
numberName = "8";
}
else if ( theRandomNum == 9) {
numberName = "9";
}
else if ( theRandomNum == 10) {
numberName = "10";
}
else if ( theRandomNum == 11) {
numberName = "Jack";
}
else if ( theRandomNum == 12) {
numberName = "Queen";
}
else if ( theRandomNum == 13) {
numberName = "King";
}
return numberName;
}
public String toString()
{
if (number() == "null") {
return ("3" + " of " + suit());
}
return (number() + " of " + suit());
}
}发布于 2015-10-28 15:10:44
首先,您的代码有一个小错误。
int theRandomNum = randomNum.nextInt(12 + 1)
但是,从下面的代码中确定您实际上是指
int theRandomNum = randomNum.nextInt(12)+1
要存储您已经拥有的卡,您只需引入一个字符串并逐步填充它,始终测试您想要接受的卡是否已经包含在此字符串中。
//This goes above the loop where you create your cards
String cards = "";
//This goes into the loop
while(cards.contains(card1.toString()){
card1 = new Cards();
}
cards += card1.toString() + "#"; //Using # as a delimiter
System.out.println(card1);
//At the end you could also print your set of cards
System.out.println(cards);这不是一种非常好的方法,因为您不允许使用数组或类似的结构,但是应该完成它的工作。
还请记住类名应该是单数的。所以不是Cards而是Card。
https://stackoverflow.com/questions/33394041
复制相似问题