我一直在試圖洗牌,但輸出有錯誤。我想讓它顯示一張隨機牌,如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