This is what you want to achieve
I replaced all BigDecimal references with Integer. If you want to keep as it then needs to make some small changes.
//This is class with main method
import java.util.Iterator;
public class IteratorPattern {
public static void main(String[] args) {
int n = 10;
FibonacciSequence fibonacciSequence = new FibonacciSequence(n);
System.out.println("iteration using iterator for-loop");
//iteration using iterator for-loop
for (Integer fibonacciNumber : fibonacciSequence) {
System.out.println(fibonacciNumber);
}
System.out.println("iteration using iterator");
//iteration using iterator
Iterator<Integer> iterator = fibonacciSequence.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
class FibonacciSequence implements Iterable<Integer>, Iterator<Integer> {
private final Integer n;
private Integer a;
private Integer b;
private int c = 1;
FibonacciSequence(Integer n) {
this.n = n;
}
@Override
public Iterator<Integer> iterator() {
return new FibonacciSequence(n);
}
@Override
public boolean hasNext() {
return c <= n;
}
@Override
public Integer next() {
c++;
if (a == null && b == null) {
a = 0;
return 0;
} else if (b == null) {
b = 1;
return b;
} else if (a == 0 && b == 1) {
a = 1;
return b;
}
Integer temp = b;
b = b + a;
a = temp;
return b;
}
}
Output :
iteration using iterator for-loop
0
1
1
2
3
5
8
13
21
34
iteration using iterator
0
1
1
2
3
5
8
13
21
34
Now the point is what changes I made.
As told by @Tom S. your hasNext method should return false if the
count reaches to n.
I changed logic in the next method. Take a look at it.