Iterate through the same methods inside objects of the same class

66 Views Asked by At

I am using greenfoot and am trying to iterate something so it is more clean. The cardsPile list is the current cards in the discard pile. I am trying to be more object oriented and am struggling with how to add multiple to the ArrayList. I am also trying to call methods inside of the Card object. I am trying to make the following process be iterable.

 card1.setLocation(100,200);
 cpu2.setLocation(100,200);
 card2.setLocation(100,200);
 cpu3.setLocation(100,200);

Since card1, etc is defined above like:

 Card card1 = cards.get(1);
 Card card2 = cards.get(2);
 Card card3 = cards.get(3);
 Card card4 = cards.get(4);
 Card cpu1 = cpuCards.get(1);
 Card cpu2 = cpuCards.get(2);
 Card cpu3 = cpuCards.get(3);
 Card cpu4 = cpuCards.get(4);

I am also trying to add them to the cardPile ArrayList by adding them by object as follows

 cardsPile.add(curCard);
 cardsPile.add(card1);
 cardsPile.add(card2);
 cardsPile.add(card3);
 cardsPile.add(card4);
 cardsPile.add(cpu1);
 cardsPile.add(cpu2);
 cardsPile.add(cpu3);
 cardsPile.add(cpu4);

Any ideas on how to iterate calling methods of the Card object are appreciated. Thank you!

1

There are 1 best solutions below

0
On

To iterate through all you variables you should store them in array or some kind of collection, like this:

see here

    ArrayList<Card> alCard = new ArrayList<Card>();
    for(int cardIdx = 1; cardIdx <= 4; cardIdx++) {
        alCard.add(cards.get(cardIdx));
    }
    ArrayList<Card> alCpu = new ArrayList<Card>();
    for(int cardIdx = 1; cardIdx <= 4; cardIdx++) {
        alCpu.add(cards.get(cardIdx));
    }

    ArrayList<Card> cardsPile = new ArrayList<Card>();
    cardsPile.add(curCard);
    for(int cardIdx = 0; cardIdx < alCard.size(); cardIdx++) {
        cardsPile.add(alCard.get(cardIdx));
    }
    for(int cardIdx = 0; cardIdx < alCpu.size(); cardIdx++) {
        cardsPile.add(alCpu.get(cardIdx));
    }