2017-01-10 155 views
-2

我有一个卡类,看起来像这样:toString方法

public class Card 
{ 
    //instance variables 
    private String faceValue; //the face value of the card 
    private String suit; //the suit of the card 
    String[] ranks = {"Ace", "2", "3", "4", "5", "6","7", "8", "9", "10", "Jack", "Queen", "King"}; 
    String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"}; 

    /** 
    * Constructor 
    */ 
    public Card() 
    { 
     for (int i = 0; i < 13; i++) 
     { 
      for (int j = 0; j < 4; j++) 
      { 
       faceValue = ranks[i]; 
       suit = suits[j]; 
      } 
     } 
    } 

    //getters 
    /** 
    * Getter for faceValue. 
    */ 
    public String getFaceValue() 
    { 
     return faceValue; 
    } 

    /** 
    * Getter for suit. 
    */ 
    public String getSuit() 
    { 
     return suit; 
    } 
    //end of getters 

    //methods 
    /** 
    * This method returns a String representation of a Card object. 
    * 
    * @param none 
    * @return String 
    */ 
    public String toString() 
    { 
     return "Dealed a card: " + faceValue + " of " + suit; 
    } 
} 

和使用该卡类来创建一个数组另一个甲板类:

public class Deck 
{ 
    //instance variables 
    private Card[] deck; 

    /** 
    * Constructor for objects of class Deck 
    */ 
    public Deck() 
    { 
     deck = new Card[52]; 
    } 

    /** 
    * String representation. 
    */ 
    public String toString() 
    { 
     return "Dealed a card: " + deck.getFaceValue() + " of " + deck.getSuit(); 
    } 
} 

我的toString方法是给我错误“无法找到符号 - 方法getFaceValue()”。相同的getSuit()。任何想法为什么?

+2

'deck'是'Card'阵列,而不是'Card'。数组没有这两种方法。 – resueman

+3

数组没有方法。数组的元素有方法。 – bmargulies

+1

您可以简单地返回'Arrays.toString(deck)',它将列出所有卡片的字符串。 –

回答

0

在这里你的问题的一些可能的解决方案的建议:

public String toString() 
{ 
    return Arrays.toString(deck); 
} 

或通过整个甲板

public String toString() 
{ 
    String deckInStringForm = "[ "; 
    for(int indexOfCard = 0; indexOfCard < deck.length; indexOfCard++) 
    { 
     deckInStringForm += deck[indexOfCard] + " "; 
    } 
    deckInStringForm += "]"; 

    return deckInStringForm; 
} 

或改变的环路/添加功能将不能像这样

指数
public String toString(int index) 
{ 
    return "Card " + index + ": " + deck[index].toString(); 
} 
1

deckCard[] deck的数组。因此,你不能调用getFaceValue()方法和getSuit()方法,因为这两种方法是Card类的一部分,而不是Card数组的一部分。