user4500435
user4500435

Reputation:

Sum all of the numerical values in an arraylist of playing cards

Im trying to add up all of the numerical values in a randomly generated deck of cards but I am having some difficulties getting it to work. So far i have:

public PackCards(int n) {
    Card c;
    pack = new ArrayList<Card>();
    for (int i = 1; i <= n; i++) {
        c = new Card();
        pack.add(c);
    }
}

public int totalPack() {
    int sum =0;
    for(int i = 0; i < pack.size(); i++)
    {
        sum = sum + pack.get(i);
    }

}

but this give me an error because i am trying to sum the arraylist of class card inestead of the cards numerical values, any idea how i can fix this? thanks

Upvotes: 0

Views: 538

Answers (3)

sprinter
sprinter

Reputation: 27976

You need to map the cards to an integer before summing. Using streams makes this more obvious:

return pack.stream()
    .mapToInt(card -> card.getIntValue())
    .sum();

Upvotes: 0

LookingForMeAreYou
LookingForMeAreYou

Reputation: 356

It's this line:

sum = sum + pack.get(i);

You have an ArrayList of class Card so get would be returning the object Card, not an integer value.

Upvotes: 2

Amir Afghani
Amir Afghani

Reputation: 38541

You need to say:

sum = sum + pack.get(i).getCardValue() or some such thing. You can't add an int with a Card object...

Upvotes: 1

Related Questions