Reputation: 23
For Example: I have a deck of cards, with a constructor Card(char,int). I initialize 52 instances of card. Then using a method within Card, I call GetName() which should return a string of char + int; So if I initialize it as Card c1 = new Card(d,1); and call c1.GetName(); it should return c1. However, the program is choosing a different card and assigning all instances of cards that name.
The Code is rather long so I have it copied here: http://pastebin.com/7akeFgs0
I've looked into Garbage Collection and I'm not sure what to do if that is the problem.
Upvotes: 0
Views: 51
Reputation: 5012
In java chars
are int
s so char + int = int
. What you likely want is "" + char + int;
which returns a String.
Also, you're really overcomplicating the deck generation. I'd suggest something like this:
public class Card
{
char suit;
int value;
public Card(char suit, int value)
{
this.suit = suit;
this.value = value;
}
public String getName()
{
return "" + suit + value;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Deck
{
static final char[] suits = new char[] {
'h', 'd', 'c', 's'
};
static final int[] values = new int[] {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13
};
List<Card> cards;
public Deck()
{
cards = new ArrayList<Card>();
for (char suit : suits)
{
for (int value : values)
{
cards.add(new Card(suit, value));
}
}
}
public void shuffle()
{
Collections.shuffle(cards);
}
}
You could also look into using Java Enums for your suits. It would allow for easy comparison and giving each suit a human readable String.
Upvotes: 0
Reputation: 4899
In your constructor
public Card(int Suitnumber, int Number){
SuitNumber = Suitnumber;}
You don't use the 2nd parameter!
Upvotes: 0
Reputation: 10717
Your variables Name, Flip, and SuitNumber should not be static. Otherwise, there's only one Name, Flip and SuitNumber for all your instances.
By the way, they should also start with a lowercase letter, but that's not related with the problem.
Upvotes: 1