我創建的紙牌遊戲程序應提示用戶輸入玩家人數以及每隻手中有多少張牌,然後洗牌,然後交易牌,然後顯示牌在每個球員手中。除非卡組中沒有足夠的卡牌(我們不能在52張卡組中處理10張10張卡牌),否則它會爲所有玩家顯示手牌。如何在java中打印嵌套在數組中的對象
我已經創建了Card類,Deck類,Hand類和驅動程序來運行程序。由於這是一項任務,我必須遵守規定,所以我只允許使用數組,而不是數組列表。我的問題是,我無法弄清楚如何在Hand對象內部打印Card對象。還有一種更好的方法可以做到這一點,但我僅限於允許導入/使用的內容。我可以獲得有關在嵌套數組內尋找打印對象的幫助嗎?由於沒有對象名稱,我無法使用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」的方法....這是最有可能的答案。 – st0le 2011-03-06 16:10:29