An ArrayList of classes. Confused

arraylist, class, coding-style, java, syntax

Solution

If you want to print the value from Cred class then fine, But if you want to print this from outside the class then yo need to add a public getter method of any private variable. Now if you just try to print the object value from outside then you need to override the toString() method:

public String toString(){
    return("Number = "+this.Number+" and Suit = "+this.Suit);
}

If you want to print outside the class,then Change your Card class like this:

public class Card
{
private String Number;
private String Suit;

public Card(String Number,String Suit)
{
this.Number=Number;
this.Suit=Suit;
}

public String getNumber() {
    return Number;
}

public void setNumber(String number) {
    Number = number;
}

public String getSuit() {
    return Suit;
}

public void setSuit(String suit) {
    Suit = suit;
}
}

Then then you can print the value like this:

List<Card> cardList = new ArrayList<Card>();
//Put some value in the list.
cardList.add(new Card("Ace","Hearts"));
//And so on..
    for (Card card : cardList) {
        System.out.println("Number = "+card.getNumber()+" Suit = "+card.getSuit());
    }

Problem

For my class lab we are to be making a Simple card deck tool that produces a standard card deck and draws 5 of them. We just learned ArrayList and how to make our own classes, but now I'm trying to put them together and it's just not working out. Here's my basic card class: ``` public class Card { private String Number; private String Suit; public Card() { Number = "Joker"; Suit = "Card"; } ``` I also have an overloaded card class, but excluding to save space. Next is the basic deck class: ``` public class Deck { private ArrayList<Card> CardDeck = new ArrayList<Card>(); public Deck() { CardDeck.clear(); CardDeck.add(new Card("Ace","Hearts")); } ``` finally, I have my client class. Right now, I'm just trying to print the generated card [Ace,Hearts]. In my card class, I have a method to print out the card's values: ``` public String print(Deck a) { return (this.Number+" of "+this.Suit); } ``` However, I'm struggling with how to print an arraylist where the list is of classes. I know right now things are a little jumbled (I'm not going to print the deck) but I figured jumping this hurdle was more important than continuing and making a hand arraylist. The problem is the same, the variables are just named different. I tried looking on the site for similar questions, but most are either just String objects or not using arraylist alltogether.

Original source

Related problems