package uebung09.iterator;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Array2dIterator<T> implements Iterator<T>{

    private T[][] array;
    private int row = 0;
    private int col = 0;

    public Array2dIterator(T[][] array) {
        this.array = array;
    }


    /**
     * Returns {@code true} if the iteration has more elements.
     * (In other words, returns {@code true} if {@link #next} would
     * return an element rather than throwing an exception.)
     *
     * @return {@code true} if the iteration has more elements
     */
    @Override
    public boolean hasNext() {
     
        while(row < array.length && (array[row] == null || col >= array[row].length)) {
            row++;
            col = 0;
        }
        return row < array.length;
    }

    /**
     * Returns the next element in the iteration.
     *
     * @return the next element in the iteration
     * @throws NoSuchElementException if the iteration has no more elements
     */
    @Override
    public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return array[row][col++];
    }


}
