我一直试图改变牌组,但输出中有错误。我想让它显示一张随机卡片,如Ace spade,两心三王等等。但结果如下所示。我如何更改我的代码?
Card@b5f53a
Card@1f6f0bf
Card@137c60d
Card@ab853b
Card@b82368
Card@11c8a71
Card@c53dce
Card@15cda3f
Card@fc9944
Card@1b26af3
Card@8b819f
Card@eb017e
Card@aeffdf
Card@120a47e
Card@f73c1
Card@789144
Card@b5f53a
Card@1893efe
Card@186c6b2
Card@15ee671
Card@eb017e
Card@137c60d
Card@16b13c7
Card@11c8a71
Card@df8f5e
Card@13d93f4
Card@1bca5f1
Card@b82368
Card@329f3d
Card@1749757
代码:
import java.util.Random;
public class deck3 {
//public int TOTALCARD;
public Card[] deck;
public deck3() {
this.deck = new Card[52];
String[] suit = {"Spades", "Hearts", "Diamonds", "Clubs"};// Array for
// suit
int[] number = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; // Array
for (int i = 0; i < suit.length; i++) {
for (int n = 0; n < number.length; n++) {
Card c = new Card(suit[i], number[n]); // Card instantiate
// Using (i*number.length + n) will get you from index 0 to 51
if (deck[(i * number.length + n)] == null) {
deck[(i * number.length + n)] = c; // Accessing index 0 to
// 51
}
}
}
}
public void CreateDeck() {}
//int[] TOTALCARD={deck};
public void shuffleDeck() {
Random generator = new Random();
for (int i = 0; i < deck.length; i++) {
int thisplace = generator.nextInt(50);
int thatplace = generator.nextInt(50);
Card savednumber = deck[thisplace];
deck[thisplace] = deck[thatplace];
deck[thatplace] = savednumber;
System.out.println(savednumber);
}
}
public void displayDeck() {
for (int i = 0; i < deck.length; i++) {
this.deck[i].display();
//shuffleDeck();// Calling the display method from my card
// class.
//System.out.println(randomNumbers);
}
}
}
答案 0 :(得分:3)
您需要在类Card中覆盖公共String toString()方法以获得漂亮的打印(而不是Card @ b5f53a,...)。 例如:
class Card {
private String value;
private Long value2;
@Override
public String toString() {
return "Card{" +
"value='" + value + '\'' +
", value2=" + value2 +
'}';
}
}
如果你需要随机播放 - 更好的方法是使用Collections.shuffle()。 例如:
Card[] cards = new Card[10];
.... // you cards array (may be you can use List?)
List<Card> cardList = new ArrayList<Card>();
Collections.addAll(cardList, cards);
Collections.shuffle(cardList);
//transform to array (if you need array)
cards = cardList.toArray(new Card[cardList.size()]);
如您所见,您可以使用list而不是array
答案 1 :(得分:0)
覆盖toString
课程中的Card
方法
然后使用相同的代码打印出Card
个对象
应该这样做。
答案 2 :(得分:0)
您的功能deck.display()
中出现错误您打印的内容是卡的类ID,而不是其数据字段。 (我建议您制作类似System.out.print(card[i])
的内容,因为程序不知道您要从类中打印什么值,因此它会打印类id)
您可能希望在display()
课程中实现功能card
,如下所示:
public void display()
{
System.out.println("Card Number = "+number+", Card Suit = "+suit);
}
然后,当您致电deck.display()
时,您可以致电card[i].display()
获取所有信用卡。
另外,请考虑使用卡片套装的int
值,这样会更轻巧。