繁体   English   中英

如何在一种以上的方法中使用数组

[英]How to use an array in more than one method

我正在尝试创建多个方法,这些方法都使用来自同一数组的数据。 方法 createDeck 工作正常。 但对于其他两种方法,它们只返回 null。 有没有办法来解决这个问题?

class Deck
{
    private static String[] suit = {"Spades", "Diamonds", "Clubs", "Hearts"};
    private static String[] rank = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", 
                                     "King", "Ace"};
    private static String[] deck = new String[52];

    // create deck
    static void createDeck()
    {
        for (int i = 0; i < deck.length; i++)
        {
            deck[i] = rank[i % 13] + " of " + suit[i / 13];
            System.out.println(deck[i]);
        }
    }

    // shuffle deck
    static void shuffleDeck()
    {
        // shuffle the deck
        for (int i = 0; i < deck.length; i++)
        {
            int index = (int) (Math.random() * deck.length);

            String temp = deck[i];
            deck[i] = deck[index];
            deck[index] = temp;
        }

        // print the shuffled deck
        for (String u : deck)
        {
            System.out.println(u);
        }
    }

    static void findTop()
    {
        System.out.println(deck[0]);
    }

}

解决此问题的一种方法是使用自动调用的静态初始化程序直接填充数组。

只需在类开头的数组声明后添加此代码块

private static String[] deck = new String[52];

static {
    for (int i = 0; i < deck.length; i++)
    {
        deck[i] = rank[i % 13] + " of " + suit[i / 13];
        System.out.println(deck[i]);
    }
}

当然删除方法createDeck因为它不再需要。 现在将正确执行以下代码并打印数组中的值

public static void main(String[] args) {
    Deck.findTop();
    Deck.shuffleDeck();
}

有关静态初始化程序的更多信息,请参阅此问题

如果它在您的对象中使用,您可以将Array放在对象的构造函数中。

public class Deck {
   String[] deck;
   public Deck(){  
       this.deck = new String[52];
   }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM