如何为面向对象编程的 int 数组编写 toString() 方法?

How do you write a toString() method for an int array for object oriented programming?

如何为 int 数组编写 toString() 方法?说 return 52 张卡包的字符串表示形式?

这是一个示例数组,作为 class 的一部分:

{
    int[] cards = new int[52];

    public void Deck()
    {
        // Setting up array
        String[] suits = {"SPADES", "CLUBS", "HEARTS", "DIAMONDS"};
        String[] ranks = {"TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", 
            "EIGHT", "NINE", "TEN", "JACK", "QUEEN", "KING", "ACE"};
        {
            // Initalising array
            for (int i = 0; i < cards.length; i++)
            {
                cards[i] = i;
            }
        }
    }

这是以面向对象的方式完成的。在这种情况下如何编写 toString() 方法以便 return 纸牌的字符串表示形式或在这种情况下为数组?

我目前使用过:

@Overide
public String toString()
{
    return getClass().getName() + "[cards[]= " + cards[] + "]";
}

我也用过类似的 toString() 方法,写成:

return getClass().getName() + "[suits[]= " + suits[] + "ranks[]= " + ranks[] + "]";

这是我用于其他值的同一种 toString() 方法,它通常有效。虽然现在我得到了两个(或者至少是第一个)的错误:

cannot find symbol
symbol: Class cards //which I dont have other than the array at the top
location: Class Pack // The class the array is currently in

unexpected type
required: value
found: class

'.class.' expected

至于打印,我希望将其格式化为列表或网格。

如果你想让它更面向对象,你应该创建一个新的 class Card.

Card class 将必须包含 suitrank 字段(此处的类型可能是 enum)。
确保 Card 覆盖 toString(),并确保 Deck 中的数组是 Card[](而不是 int[])。

现在您可以通过调用 Arrays.toString() 轻松实现 toString(),这将依次调用每个 Card 对象的 toString(),从而产生所需的表示形式你的套牌。


至于你的代码(后来加的):

return getClass().getName() + "[cards[]= " + cards[] + "]";

不会编译,因为 cards[] 不是一个值 - cards 是,但它不会给你你想要的。数组的 toString() 不产生 array, and you should use Arrays.toString(cards).

的内容

但是,我建议按照此答案开头所述重新设计代码。