samedi 17 décembre 2016

Java - else if statement never gets executed?

I'm writing my own iterator that will first return list elements in odd positions then in even. It does traverse it in odd positions but never in evens, it seems that it won't execute the code in the else-if statement and I'm not sure why.

The input list is quite large, so you can check it here (pastebin).

Code:

public class OddEvenIterator implements Iterator<Card>{
        static final long serialVersionUID = 101L;
        private ArrayList<Card> cards;
        private int next;
        private boolean odds;

        public OddEvenIterator(ArrayList<Card> cards){
            this.cards = cards;
            next = -2;
            odds = true;
        }

        @Override
        public Card next(){
            if(hasNext()){
                return cards.get(next+=2);
            }else if(odds){
                next = -1;
                odds = false;

                if(hasNext()){
                    return cards.get(next+=2);
                }
            }

            return null;
        }

        @Override
        public boolean hasNext() {
            return cards.size() - next - 1 >= 2;
        }

Output:

TWO of SPADES
TWO of DIAMONDS
THREE of SPADES
THREE of DIAMONDS
FOUR of SPADES
FOUR of DIAMONDS
FIVE of SPADES
FIVE of DIAMONDS
SIX of SPADES
SIX of DIAMONDS
SEVEN of SPADES
SEVEN of DIAMONDS
EIGHT of SPADES
EIGHT of DIAMONDS
NINE of SPADES
NINE of DIAMONDS
TEN of SPADES
TEN of DIAMONDS
JACK of SPADES
JACK of DIAMONDS
QUEEN of SPADES
QUEEN of DIAMONDS
KING of SPADES
KING of DIAMONDS
ACE of SPADES
ACE of DIAMONDS

Aucun commentaire:

Enregistrer un commentaire