helen986
helen986

Reputation: 31

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. But for the other two methods, they just return 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]);
    }

}

Upvotes: 1

Views: 530

Answers (2)

TorpedoCoder
TorpedoCoder

Reputation: 1

If it is used in your object, you can put the Array inside the constructor of an object.

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

Upvotes: 0

Joakim Danielson
Joakim Danielson

Reputation: 52013

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. 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

Upvotes: 1

Related Questions