简体   繁体   English

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

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

I am trying to create mutliple methods which all use data from the same array.我正在尝试创建多个方法,这些方法都使用来自同一数组的数据。 The method createDeck works fine.方法 createDeck 工作正常。 But for the other two methods, they just return null.但对于其他两种方法,它们只返回 null。 Is there a way to fix this?有没有办法来解决这个问题?

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]);
    }

}

One way to solve this is to directly fill the array using a static initalizer which gets called automatically.解决此问题的一种方法是使用自动调用的静态初始化程序直接填充数组。

Just add this code block after the decalration of the array at the beginning of the class只需在类开头的数组声明后添加此代码块

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]);
    }
}

And of course remove the method createDeck since it is no longer needed.当然删除方法createDeck因为它不再需要。 The following code will now be executed correctly and printing values from the array现在将正确执行以下代码并打印数组中的值

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

See this question for more info on static initializer有关静态初始化程序的更多信息,请参阅此问题

If it is used in your object, you can put the Array inside the constructor of an object.如果它在您的对象中使用,您可以将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