使用类构造函数初始化另一个类中的对象时出现问题

时间:2015-12-27 22:46:05

标签: java class oop constructor

我之前发布了一个与同一问题相关的问题,但这次我的问题完全不同,所以请在将此标记为重复或向下注释之前先听取我的意见。

因此,对于我的任务,我应该创建一个名为“Card”的类,它代表一个标准的扑克牌,其中西装和面部由数字代表(1-4代表西装,1-13代表面部),还有构造函数初始化卡片,mutator和accessor函数来更改卡片对象并输出其字符串表示(例如,King of Hearts)。然后我不得不创建另一个名为DeckOfCards的类,它代表一副52张牌,存储52张Card对象。这个类有一个构造函数来初始化一个带有标准52卡的牌组,并且成员函数可以对牌组进行洗牌,处理牌并打印牌组中的所有牌。我的问题是试图让这个DeckOfCards类的构造函数工作。这是整个类的代码,我的特殊问题是构造函数方法:

public class DeckOfCards
{
/*Class that stores 52 objects of the Cards class.  Include methods to shuffle the deck, 
 * deal a card, and report the number of cards left in the deck, and print all the cards in
   the deck.*/
 private Card[] deck = new Card[52];
 private int count = 52, j = 0;

 public DeckOfCards()/*Constructor initializes the deck with 52 cards*/
 {
     int i = 0;

     for (int suit = 0;suit < 4;suit++)
     {
         for (int face = 0;face < 13;face++)
         {
             deck[i] = Card(suit, face);
             i++;
         }
     }
 }

 public String toStringDeck()//Prints all the cards in the deck
 {
     String deckPrint = "";
     for (int i = 0; i < 52;i++)
     {
         deckPrint += deck[i].toString() + "\n";
     }

     return deckPrint;
 }

 public void shuffle()//Shuffles the deck
 {
     Random generator = new Random();
     int rand1, rand2;
     Card temp;

     for (int i = 0;i < 100;i++)
     {
         rand1 = generator.nextInt(52);
         rand2 = generator.nextInt(52);
         temp = deck[rand1];
         deck[rand1] = deck[rand2];
         deck[rand2] = temp;
     }
 }

 public void deal()/*Deals a card from the deck and prints it as its dealt. Reports the number
 of cards remaining in the deck.*/
 {
     String deal;

     if (j < 52)
     {
         deal = deck[j].toString();
         j++;
         System.out.println(deal);
         count--;
         System.out.println("There are " + count + " cards remaining in the deck.");
     }
     else
     {
         System.out.println("There are no cards remaining in the deck.");
     }
 }

}

当我尝试编译时,我收到错误:“找不到符号 - 方法卡(int,int)。”

我无法理解为什么在构造函数中,我无法创建Card对象并在此处初始化它。如果我需要提供更多详细信息,请告诉我。感谢。

1 个答案:

答案 0 :(得分:2)

您忘记了new关键字。变化

deck[i] = Card(suit, face);

deck[i] = new Card(suit, face);

&安培;确保您在Card课程中定义了 2-args 构造函数。