LordValkyrie
LordValkyrie

Reputation: 75

Output of card shuffle using arraylists not displaying

Everything works here except trying to show the Deck after I shuffle it. I'm not sure why, but the arraylist seems to be empty after shuffling. If I comment out the shuffling code, the Deck displays, but unshuffled, obviously. Since this is an assignment, I need my program to stay in the same general format, and the algorithm for shuffling needs to remain the same as much as possible.

public class Shuffler
{
    public static void selectionShuffle(ArrayList<Card> values) {
    ArrayList<Card> shuffled = new ArrayList<Card>();
    ArrayList<Card> copy = new ArrayList<Card>();
    for (int k = 51; k >= 0;) {
        int r = (int)(Math.random() * (double)52);
        if (r < values.size()) {
            shuffled.add(values.get(r));
            values.remove(r);
            k--;
        }
    }
    for (int i = 0; i < values.size(); i++) {
        values.set(i, shuffled.get(i));
    }


}

Here is the Deck Constructor, it creates a deck out of three arrays to form three card objects.

public class Deck
{
    public static ArrayList<Card> cards = new ArrayList<Card>();
    private int size;
    public Deck(String[] ranks, String[] suits, int[] values) 
    {
        for (int i = 0; i < values.length; i++) {
            cards.add(new Card(ranks[i], suits[i], values[i]));
        }
        size = values.length;
        shuffle();
    }

    public void shuffle() {
        Shuffler.selectionShuffle(cards);
        size = size();
    }
}

Upvotes: 0

Views: 454

Answers (2)

Marko Gresak
Marko Gresak

Reputation: 8207

Java passes object by reference, meaning that if your function is manilupating changed object, it will also be changed after function call.

Here you call selectionShuffle:

public void shuffle() {
    Shuffler.selectionShuffle(cards);
    size = size();
}

And the selectionShuffle function manipulates passed list cards. Because you call values.remove(r);, your list is is empty when function finishes.

A simple solution would be to create a copy of passed values and manipulate the copy. The ArrayList has a constructor to do this.

Upvotes: 0

brso05
brso05

Reputation: 13232

This should be:

for (int i = 0; i < shuffled.size(); i++) {
    values.add(shuffled.get(i));
}

Problem is you had:

for (int i = 0; i < values.size(); i++) {
    values.set(i, shuffled.get(i));
}

The size of values at this point is 0 so it won't do anything...You removed all elements from values so it will have size 0.

Upvotes: 2

Related Questions