我遇到问题让我的代码洗牌。我想我对collections.shuffle的语法错了。我目前拥有的代码并没有洗牌。下面是甲板类和卡类。 deck类包含collections.shuffle方法。
甲板课
public class Deck {
private Card[] deck = new Card[52];
private int topCard;
Deck() {
topCard = 0;
for (int i = 0; i < deck.length; i++)
deck[i] = new Card(i);
}
public void shuffle() {
topCard = 0;
Collections.shuffle(Arrays.asList(deck));
}
public Card dealCard() {
Card theCard;
if (topCard < deck.length) {
theCard = deck[topCard];
topCard++;
}
else
theCard = null;
return theCard;
}
}
卡类
public class Card {
private int cardNum;
final static String[] suits = {"Spades", "Hearts", "Diamonds", "Clubs"};
final static String[] ranks = {"Ace", "2", "3","4","5","6","7","8", "9","10", "Jack", "Queen", "King"};
Card (int theCard) {
setCardNum (theCard);
}
public void setCardNum (int theCard) {
cardNum = (theCard >= 0 && theCard <= 52)? theCard: 0;
}
public int getCardNum() {
return cardNum;
}
public String toString() {
return ranks[cardNum%13] + " of " + suits[cardNum/13];
}
public String getSuit() {
return suits[cardNum/13];
}
public String getRank() {
return ranks[cardNum%13];
}
public int getValue() {
return cardNum%13;
}
}
答案 0 :(得分:2)
下面是一个类似问题的示例代码,其中我们被要求不使用任何内置函数来重新组合套牌,但允许使用Math.random()。
import java.util.*;
class Card {
private String rank;
private String suit;
public Card(String r,String s) {
rank=r;
suit=s;
}
public String getRank() {
return rank;
}
public String getSuit() {
return suit;
}
public String toString() {
return rank+" of "+suit;
}
}
class Deck {
private ArrayList<Card> deck;
private String[] ranks ={"ACE","2","3","4","5","6","7","8","9","10","JACK","QUEEN","KING"};
private String[] suits ={"SPADE","HEART","CLUB","DIAMOND"};
public Deck() {
deck = new ArrayList<Card>();
for(int i=0;i<suits.length;i++) {
for(int j=0;j<ranks.length;j++) {
deck.add(new Card(ranks[j],suits[i]));
}
}
}
public void showCards() {
System.out.println("\n\n Showing Cards !!!");
int i=1;
for(Card c:deck) {
System.out.println("Card "+(i++)+" : "+c);
}
}
public void shuffle() {
ArrayList<Card> temp = new ArrayList<Card>();
while(!deck.isEmpty()) {
int loc=(int)(Math.random()*deck.size());
temp.add(deck.get(loc));
deck.remove(loc);
}
deck=temp;
}
}
public class Game {
public static void main(String[] args) {
Deck myDeck = new Deck();
myDeck.showCards();
myDeck.shuffle();
myDeck.showCards();
}
}