我试图制作一个甲板改组方法。我在Stack Overflow上搜索了答案,但一直无法弄明白。
我想创建一个shuffle方法。此方法将从0到甲板大小之间的数组中选取两个随机数。然后我希望将这两个数字作为参数传递给我的swap()方法。我想创建一个循环,以便交换方法被调用TIMES_TO_SHUFFLE次。这样做的最佳方式是什么?
这是甲板课。
import java.util.ArrayList;
/**
* Deck of cards.
* @author Stefan
* @version 2014.11.19
*/
public class Deck {
private ArrayList<Card> deck;
public static final int TIMES_TO_SHUFFLE = 10;
/**
* Constructor for objects of class Deck
* Creates a new container for Card objects
*/
public Deck() {
deck = new ArrayList<Card>();
}
/**
* Swap two cards that the user chooses.
*/
public void swap(int indexA, int indexB) {
Card temp = deck.get (indexA);
deck.set(indexA, deck.get (indexB));
deck.set(indexB, temp);
}
/**
* Shuffles two cards by passing parameters to the swapCards method
*/
private void shuffle() {
}
/**
* Add a card to the deck.
* @param Card to be added
*/
public void addCard(Card cardToAdd) {
deck.add(cardToAdd);
}
/**
* Take the first card from the deck.
* @return Card or null
*/
public Card takeCard() {
if(deck.isEmpty()) {
return null;
} else {
// get the top card
return deck.remove(0);
}
}
/**
* Show the contents of the deck.
*/
public void showDeck() {
for(Card eachCard : deck) {
System.out.println(eachCard.getDescription()+
" of " + eachCard.getSuit());
}
}
}
这是卡类。
/**
* Card class - a typical playing card.
*
* @author Stefan
* @version 2014.11.18
*/
public class Card {
private String suit;
private int value;
private String description;
/**
* @default constructor
*/
public Card(){
}
/**
* Constructor for objects of class Card
* @param suit e.g. "Hearts"
* @param value e.g. 10
* @param description e.g. "Ten"
*/
public Card(String description, String suit, int value) {
this.suit = suit;
this.value = value;
this.description = description;
}
/**
* @return the suit
*/
public String getSuit() {
return suit;
}
/**
* @param suit the suit to set
*/
public void setSuit(String suit) {
this.suit = suit;
}
/**
* @return the value
*/
public int getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(int value) {
this.value = value;
}
/**
* @return the description
*/
public String getDescription() {
return description;
}
/**
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
}
答案 0 :(得分:0)
shuffle方法如下所示:
private void shuffle() {
Deck ob = new Deck();
int x = deck.size() - 1;
for(int i = 0; i < TIMES_TO_SHUFFLE + 1; i ++){
int r1 = (int) Math.floor(Math.random() * x);
int r2 = (int) Math.floor(Math.random() * x);
ob.swap(r1, r2);
}
}