我一直在试图洗牌,但输出有错误。我想让它显示一张随机牌,如Ace spade,两心三王等。但是,结果如下所示。我如何更改我的代码?如何在Java中洗牌甲板?
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
代码:
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);
}
}
}
您也可以使用'Collections.shuffle' – cybersoft 2014-12-07 10:08:10
打印此输出的方法是什么?另请发布您的'Card.display()'实现。 – Elist 2014-12-07 10:21:08
添加一个公共字符串toString(),它打印套装和数字。 – 2014-12-07 10:35:41