package misc;

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

public class FibonacciSequence implements Iterable<Integer> {

	private int n;

	public FibonacciSequence(int n) {
		// Iterate over the first n elements of the Fibonacci sequence
		this.n = n;
	}

	public Iterator<Integer> iterator() {
		
		// Return an instance of an anonymous inner class
		return new Iterator<Integer>() {
			private int a = 0, b = 1, i = 0;

			public boolean hasNext() {
				return i < n;
			}

			public Integer next() {
				if(!hasNext()) 
					throw new NoSuchElementException();

				switch(i++) {
				case 0: 
					return 0;
				case 1: 
					return 1;
				default: 
					int c = a + b;
					a = b; 
					b = c; 
					return c;
				}
			}

			public void remove() {
				throw new UnsupportedOperationException();
			}
		};
	}

	public static void main(String[] args) {
		// Test the class by printing the first 15 fibonacci numbers
		for(int f : new FibonacciSequence(15)) {
			System.out.println(f);
		}	
	}
}

