【发布时间】:2011-03-06 16:03:58
【问题描述】:
我正在创建的纸牌游戏程序应该提示用户输入玩家人数,以及每手有多少张牌,然后洗牌,然后发牌,然后显示每个玩家手中的牌。它将显示所有玩家的手牌,除非牌组中的牌不足(我们不能从 52 张牌的牌组中处理 10 张牌,共 7 张牌)。
我创建了一个 Card 类、一个 Deck 类、一个 Hand 类和驱动程序来运行程序。由于这是一项任务,我必须遵守给定的规则,所以我只能使用数组,而不是数组列表。我的问题是我无法弄清楚如何在 Hand 对象中打印 Card 对象,在 Hands 数组中。也可能有更好的方法来做到这一点,但我仅限于我被允许导入/使用的内容。我可以在哪里寻找嵌套数组中的打印对象获得一些帮助吗?由于没有对象名称,我无法使用在 Hand 类中编写的方法将卡片添加到数组中的 Hands 中。
编辑:我让 Hand 类中的构造函数在传递给它的 int 上创建一个手大小。令人困惑的是,当我从用户那里得到确实有多少玩家在玩游戏时,我在驱动程序中创建了一个 Hand 类型的数组,其中使用循环填充了新的 Hand 对象。那时我不知道如何引用每个单独的手对象,因此我可以使用 toString() 打印内容。他们似乎没有名字。
要遵循的代码:
import java.util.Arrays;
import java.util.Scanner;
public class CardsDriver {
public static void main(String[] args)
{
Card c1 = new Card(); //create new card object
Scanner kb = new Scanner(System.in);
int cards;
int players;
System.out.print("How many players are in the game?");
players = Integer.parseInt(kb.nextLine());
System.out.print("\nHow many cards will be dealt to each player?");
cards = Integer.parseInt(kb.nextLine());
while ((cards * players) > 52)
{
System.out.print("There are not enough cards in the deck to deal " +
players + " hands of " + cards + " cards. try again.");
System.out.print("How many players are in the game?");
players = Integer.parseInt(kb.nextLine());
System.out.print("\nHow many cards will be dealt to each player?");
cards = Integer.parseInt(kb.nextLine());
}
Deck readyDeck = new Deck(); //create new deck
readyDeck.shuffleDeck(); //shuffle the newly built deck using Java.Util.Random
Hand[] playerHands= new Hand[players]; //create another array to hold all player hands
for(int index =0; index < playerHands.length; index++)
{
playerHands[index] = new Hand(cards); //create hand object for each player of the size input by the player
/*for (int index2 =0; index2<cards;index2++)
{
//fill each hand with cards using addcard somehow. i have no object name.
Hand.addCard(readyDeck.dealACard());
}*/
}
}
【问题讨论】:
-
我不明白...问题是什么? :-\ 但我会回答“覆盖 toString”方法....这是最有可能的答案。