-2

I am trying to solve a question that provided the following classes to me. How can I create a custom iterator class DeckIterator that will help me iterate the Card[] deck array in the Deck class?

I have a Card class that looks like this:

public class Card {

    private char suit;
    private int value;

    public Card (char s, int v)
    {
        this.suit = s;
        this.value = v;
    }
}

And I have a Deck class that looks like this:

public class Deck {

    private Card[] deck;
    private int idx;

    public Deck (int size) 
    {   
        this.deck = new Card[size];
        this.idx = 0;
    }
}

Thanks a lot

muffin
  • 668
  • 1
  • 6
  • 13
Joe
  • 2,543
  • 3
  • 25
  • 49
  • Did you try anything? – Oliver Charlesworth Jul 05 '14 at 15:58
  • you should implement Iterable interface properly. http://tutorials.jenkov.com/java-generics/implementing-iterable.html – Juvanis Jul 05 '14 at 15:58
  • @OliCharlesworth i did, I know I should implements iterable in the deck class and iterator in DeckIterator class, but I have no clue how to use it to iterate in a deck of cards that is an array...:/ please help me – Joe Jul 05 '14 at 16:05
  • 1
    why don't you use List instead of the array? the iterator comes for free with the list – wastl Jul 05 '14 at 16:16
  • @wastl i know, but I am trying to solve a question that provide me those classes and I need to use what I have. – Joe Jul 05 '14 at 16:17

1 Answers1

1

Add this to class Deck implements Iterable<Card>

public Card getCard( int i ){
    return deck[i];
}

public Iterator<Card> iterator(){
    return new DeckIterator( this );
}

public class DeckIterator implements Iterator<Card> {
    private Deck d;
    private int pos;
    DeckIterator( Deck d ){
        this.d = d;
    }

    @Override
    public boolean hasNext(){
        return pos < d.deck.length;
    }

    @Override
    public Card next(){
        if( pos >= d.deck.length ){
            throw new NoSuchElementException( "no more cards in deck" );
        }
        return d.getCard( pos++ );
    }

    @Override
    public void remove(){
        throw new UnsupportedOperationException( "not implemented" );
    }
}

Suit might be iimplemented as an enum, as might rank.

laune
  • 31,114
  • 3
  • 29
  • 42