I am trying to write a solitiare game on java. I'm trying to add the card objects to my arraylist but the MakeDeck function is not working properly.
public class PileOfCards {
public ArrayList<Card> pile = new ArrayList<Card>();
Card tempo;
public PileOfCards() {
pile = new ArrayList<Card>();
}
public void MakeDeck() {
for (int i=0;i<13;i++){
tempo = new Card(i+1, "FaceDown", "Clubs");
pile.add(tempo);
}
for (int j=0;j<13;j++){
tempo = new Card(j+1, "FaceDown", "Diamonds");
pile.add(tempo);
}
for (int k=0;k<13;k++){
tempo = new Card(k+1, "FaceDown", "Hearts");
pile.add(tempo);
}
for (int l=0;l<13;l++){
tempo = new Card(l+1, "FaceDown", "Spades");
pile.add(tempo);
}
}
When I'm trying to print the values it prints "0, null, null" , 52 times. What is the problem? It looks like I can't reach to the ArrayList, but I don't know why.
Edited:
Card constructor:
public Card(int valueTemp, String suitTemp, String statusTemp) {
valueTemp = value;
suitTemp = suit;
statusTemp = status;
}
Print function:
public void printPile(){
for(int i=0;i<pile.size();i++){
System.out.print(pile.get(i).status);
System.out.print(" ");
System.out.print(pile.get(i).suit);
System.out.print(" ");
System.out.print(pile.get(i).value);
System.out.printf("\n");
}
The issue is in your Card
constructor; the assignments are the wrong way around.
You want
public Card(int valueTemp, String suitTemp, String statusTemp) {
value = valueTemp;
suit = suitTemp;
status = statusTemp;
}
The other way around doesn't set the fields equal to the parameters, it sets the parameters equal to the fields. Specifically, what you had before
public Card(int valueTemp, String suitTemp, String statusTemp) {
valueTemp = value;
suitTemp = suit;
statusTemp = status;
}
sets valueTemp
to value
, suitTemp
to suit
, and statusTemp
to status
, when you actually wanted to do the other way around in your constructor.
public Card(int valueTemp, String suitTemp, String statusTemp) {
valueTemp = value;
suitTemp = suit;
statusTemp = status;
}
All those assignments are back to front. You are assigning to the parameters instead of from them. It is customary to write it like this:
public Card(int value, String suit, String status) {
this.value = value;
this.suit = suit;
this.status = status;
}
The assignments are backwards.
lValue = rValue
;
lValue
is the thing you want to set while rValue
is the data you want it to become.
When you did:
public Card(int valueTemp, String suitTemp, String statusTemp) {
valueTemp = value;
suitTemp = suit;
statusTemp = status;
}
You're changing the parameters valueTemp
, suitTemp
, and statusTemp
which you passed in as parameters to whatever value
, suit
, and status
are.
To fix this, flip around the values you're assigning like so:
public Card(int valueTemp, String suitTemp, String statusTemp) {
value = valueTemp;
suit = suitTemp;
status = statusTemp;
}