这个程序应该使用ArrayList来创建一副牌。用户输入要绘制的卡数和打印的卡,然后打印保留在卡座中的其余卡。我拿到了用户的卡片进行打印,但我无法弄清楚如何将剩余的卡片打印到卡座中。任何帮助将不胜感激。
public class Card
{
private int type, value;
private String[] cardType = {"Clubs", "Spades", "Diamonds", "Hearts"};
private String[] cardValue = {"Ace", "King", "Queen", "Jack", "10",
"9", "8", "7", "6", "5", "4", "3", "2"};
public Card(int types, int values)
{
type = types;
value = values;
}
public String toString()
{
String finalCard = cardValue[value] + " of " + cardType[type];
return finalCard;
}
}
import java.util.Random;
import java.util.ArrayList;
public class Deck
{
private ArrayList<Card> cards;
public Deck()
{
cards = new ArrayList<Card>();
for(int a =0; a<=3; a++)
{
for(int b =0; b<=12;b++)
{
cards.add(new Card(a,b));
}
}
}
public Card drawRandomCard()
{
Random generator = new Random();
int index = generator.nextInt(cards.size());
return cards.remove(index);
}
public String toString()
{
String result = "Cards remaining in deck: " + cards;
return result;
}
}
import java.util.Scanner;
public class CardProgram
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
Card C;
Deck deck = new Deck();
System.out.println("Enter number of cards to be dealt: ");
int numberCards = scan.nextInt();
System.out.println("Cards drawn: ");
for(int i=0; i<numberCards; i++)
{
C = deck.drawRandomCard();
System.out.println(C.toString());
}
//C = deck.toString();
//System.out.println(cards.toString());
// System.out.println(C.toString());
}
}
答案 0 :(得分:2)
我认为这应该做你的工作
System.out.println(deck.toString());
//System.out.println(deck); // Note : this will also work
虽然我认为创建一个新方法remainingCard
并返回cards
ArrayList是有意义的,而不是用剩余的卡覆盖toString
。
答案 1 :(得分:0)
for(int i=0; i<deck.cards.size(); i++)
{
System.out.println(deck.cards.get(i).toString());
}
在你有一个for循环打印掉你绘制的卡后,立即试试这个循环
你在主要方法中有一个牌组......牌组有牌......你从牌组中抽出一些牌......然后你说deck.cards会给你牌组卡牌列表..然后你说.get(i)将每张牌放到那张牌中......最后.toString()打印出牌的内容
注意:你必须在你的套牌类中公开私人数组列表,或者在套牌类中添加一个公共getter方法来获得卡片的arraylist ......