Search code examples
javaarrayslistoopsuperclass

I can't get my card objects to print correctly


This is the method I'm trying to display which is supposed to be a 4x4 grid of cards. I feel like there is something wrong possible inside the card objects? This is what I get when i try to run what's in printHiddenCard.

edu.cpp.cs.cs141.memgame.QCard@182decdb 
edu.cpp.cs.cs141.memgame.StarCard@26f0a63f 
edu.cpp.cs.cs141.memgame.PercCard@4361bd48 
edu.cpp.cs.cs141.memgame.PercCard@4361bd48 
edu.cpp.cs.cs141.memgame.MinusCard@53bd815b 
edu.cpp.cs.cs141.memgame.MinusCard@53bd815b 
edu.cpp.cs.cs141.memgame.PoundCard@2401f4c3 
edu.cpp.cs.cs141.memgame.QCard@182decdb 
edu.cpp.cs.cs141.memgame.SlashCard@7637f22 
edu.cpp.cs.cs141.memgame.ExclCard@4926097b 
edu.cpp.cs.cs141.memgame.StarCard@26f0a63f 
edu.cpp.cs.cs141.memgame.PlusCard@762efe5d 
edu.cpp.cs.cs141.memgame.PlusCard@762efe5d 
edu.cpp.cs.cs141.memgame.SlashCard@7637f22 
edu.cpp.cs.cs141.memgame.ExclCard@4926097b 
edu.cpp.cs.cs141.memgame.PoundCard@2401f4c3



private static int rows = 4;
private static int columns = 4;
    public static Card[][] card = new Card[rows][columns];

 public Card[][] printHiddenCard() {

    QCard c1 = new QCard();
    StarCard c2 = new StarCard();
    MinusCard c3 = new MinusCard();
    PoundCard c4 = new PoundCard();
    ExclCard c5 = new ExclCard();
    PercCard c6 = new PercCard();
    SlashCard c7 = new SlashCard();
    PlusCard c8 = new PlusCard();

    List<Card> allCards = Arrays.asList(c1, c2, c3, c4, c5, c6, c7, c8);
    List<Card> list = new ArrayList<>(allCards);
    list.addAll(allCards);
    Collections.shuffle(list);

    int counter = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            card[i][j] = list.get(counter++);
            System.out.println(card[i][j] + " ");
        }
    }
    return card;
}

This is what one of the card objects look like:

public class QCard extends Card {

public QCard() {
    super("?");
}

}

And this is the superclass:

public abstract class Card {

private String cardType = "";
private boolean isFlipped = false;

public Card(String cardType) {
    this.cardType = cardType;
}

public String getCardType() {
    return cardType;
}

public boolean isFlipped() {
    return isFlipped;
}

public void setFlipped(boolean isFlipped) {
    this.isFlipped = isFlipped;
}

}


Solution

  • You should override the toString() method in the object you want to print, like this:

    public class QCard extends Card {
        public QCard() {
            super("?");
        }
    
        public String toString() {
            return "card data";
        }
    }
    

    The above example will always print card data, so add the fields you want to include in your printOut.