gpt4 book ai didi

Java 洗牌牌

转载 作者:行者123 更新时间:2023-12-02 05:41:00 26 4
gpt4 key购买 nike

我在让我的代码洗牌时遇到问题。我认为 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;
}
}

最佳答案

这里是一个类似问题的示例代码,其中我们被要求不要使用任何内置函数来洗牌,但允许使用 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();
}

}

关于Java 洗牌牌,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24520782/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com