0

I'm having trouble with a class I wrote containing an ArrayList. Code:

import java.util.ArrayList;


public class AscendingPile {
 public ArrayList<Integer> pile = new ArrayList<Integer>() {{
     add(1);
 }};

public void lay(int card) throws IllegalArgumentException{
    int lastCard = pile.get(pile.size() - 1);
    if(card > lastCard || card == lastCard - 10){
        pile.add(card);
    }
    else {
        throw new IllegalArgumentException("....");
    }
}
// returns last card on the deck
public int getCard() {
    return pile.get(pile.size() - 1);
}

}

Problem is the lay method: Instead of defining a new local variable I want the if statement to look something like this:

if(card > pile.getCard() || card == pile.getCard() - 10)

but IntelliJ says cannot resolve symbol getCard()

How can I change my code to obtain the desired result?

Pedro del Sol
  • 2,840
  • 9
  • 39
  • 52
fatso88
  • 7
  • 6
  • 2
    That's because `getCard()` is not a method defined on `ArrayList`. – azurefrog Mar 15 '17 at 14:46
  • `getCard` is not a method of class `ArrayList`, so you cannot call `getCard` on `pile` which is what you are doing: `pile.getCard()`. Just call `getCard()`, not `pile.getCard()`. – Jesper Mar 15 '17 at 14:47
  • Also, check this, might be interesting for improving your code: http://stackoverflow.com/a/14072408/7709364 – Tanguy Labrador Ruiz Mar 15 '17 at 15:07

2 Answers2

1

but IntelliJ says cannot resolve symbol getCard()

That is true, ArrayList class has no method called getCard()

instead of doing:

pile.getCard();

do call directly the method of the class AscendingPile

getCard();
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

As already said, just call directly getCard().

I'm also currently coding a card game. Instead of using ArrayList for your deck, i strongly recommend you to use Stack instead. (see documentation https://docs.oracle.com/javase/7/docs/api/java/util/Stack.html).

Stack provides you useful methods like pop() and push().

Pop removes the object at the top of the stack, just like you're doing now with your getCard() method.

  • thank you for your feedback. Unfortunatelly it's an Assignment and we can't use Stack for now. But I'll keep it in mind for future projects! – fatso88 Mar 16 '17 at 00:03
  • I'm coding for assignments too, and i can tell you that taking initiatives is very relevant and well welcomed by teachers in this kind of cases :) – Tanguy Labrador Ruiz Mar 16 '17 at 08:51