首先,我制作了卡片牌的副本。然后,我尝试使用我创建的方法仅打印该副本甲板的前七个卡(我需要做2次)。NextCard是跟踪我们在甲板上的位置的反面。
这是我的班级:公共班级甲板
{
private Card[] deck;
private int nextCard;
public Deck(){
deck = new Card[53];
nextCard = 0;
for(int i = 0; i < 52; i++){
deck[i] = new Card(i);
nextCard++;
}
}//Deck
public Deck(Deck existingDeck){//copy
this.deck = new Card[52];
for(int i=0; i < 52; i++){
this.deck[i] = new Card(existingDeck.deck[i]);
}
nextCard++;
}
public void shuffle(){
Card crdTemp = new Card();
Random random = new Random();
int num;
nextCard = 0;
for(int i = 0; i < 52; i++){
num = random.nextInt (51);
crdTemp = deck[i];
deck[i] = deck[num];
deck[num] = crdTemp;
nextCard++;
}
}
public Card dealACard(){
Card crd = null;
if(nextCard > -1){
crd = deck[nextCard];
nextCard--;
}
return crd;
}
public String dealAHand(int handSize){
Card crd = null;
String cards = "";
for(int i = 0; i < handSize; i++){
crd = dealACard();
cards += crd.toString();
//cards += dealACard().toString();
}
return cards;
}
public String toString(){
String info = "";
for(int i = 0; i < 52; i++){
deck[i].toString ( );
info += deck[i];
nextCard++;
}
return info;
}
}
然后,在我的驱动程序中:
Deck bDeck = new Deck(aDeck);
bDeck.toString();
String[] sevenCards = new String[bDeck];
for(int i = 0; i < 7; i++){
System.out.println ("Copy deck: ");
sevenCards[i] = bDeck.toString();
}
for(int i = 0; i < 7; i++){
System.out.println (sevenCards[i]);
}
}
我假设我将整个bdeck分配给每个Sevencards数组元素,但是我不知道该如何做不同。我还认为,没有尝试创建这样的新数组的方法可以做到这一点,但是再次,我经历了许多不同的想法,没有任何措施。非常感谢某个方向,谢谢。
如果我正确理解您,您只想打印甲板的前七张卡片?因此,您必须访问甲板卡才能这样做:
Deck bDeck = new Deck(aDeck);
bDeck.toString();
String[] sevenCards = new String[7];
for(int i = 0; i < 7; i++){
System.out.println ("Copy deck: ");
sevenCards[i] = bDeck.deck[i];
}
for(int i = 0; i < 7; i++){
System.out.println (sevenCards[i]);
}
}
如果您可以在循环中访问Deck.deck
,并且您正确实现了Card
类的toString()
方法。
编辑:这是dealACard()
的最终更改:
public Card dealACard(){
Card crd = null;
if(nextCard > 0) {
nextCard--;
crd = deck[nextCard];
}
return crd;
}