Java poker deck all same cards

I've created a deck Card[52] theDeck and it seems to only contain Kings of Spades. I don't think anything wrong with the constructor, but I'm new to java, so I might be wrong... Here's the deck constructor:

public class Deck {

private Card[] theDeck; 
private int top; 
// add more instance variables if needed

public Deck(){
    theDeck = new Card[52];
    for(int s = 1; s <= 4; s++)
    {
        for (int v = 1; v <= 13; v++)
        {
            for (int i = 0; i < theDeck.length; i++)
            {

                theDeck[i] = new Card(s,v);
            }
        }
    }   
}

It should be creating 52 distinct Card objects, but when I print it, every card is Card(4,13) -- King of Spades.

Here's the Card constructor just in case:

public class Card implements Comparable<Card>
{

private int suit; 
private int value; 

public Card(int s, int v)
{ //constructor of an object Card
    suit = s;
    value = v;
    //make a card with suit s and value v
}
Jon Skeet
people
quotationmark

You've got three loops, and your inner loop goes through the whole range of the deck - and assigns a card to it which doesn't depend on the index:

for (int i = 0; i < theDeck.length; i++)
{
    theDeck[i] = new Card(s,v);
}

So for each value of s and v you're overwriting the whole deck with the same card. The final card you create is the king of spades, hence the problem.

I suspect you don't want that inner loop at all - instead, work out the index to use based on s and v:

for (int s = 1; s <= 4; s++)
{
    for (int v = 1; v <= 13; v++)
    {
        int index = (s - 1) * 13 + (v - 1);
        theDeck[index] = new Card(s, v);
    }
} 

Or keep a separate index variable and just increment that:

int index = 0;
for (int s = 1; s <= 4; s++)
{
    for (int v = 1; v <= 13; v++)
    {
        theDeck[index] = new Card(s, v);
        index++;
    }
} 

people

See more on this question at Stackoverflow