0
    public BigDecimal next() {

        for (int i = 1; i < 100; i++) {
            BigDecimal cur = new BigDecimal(1);
            BigDecimal prev = new BigDecimal(0);

            final BigDecimal next = cur.add(prev);
            prev = cur;
            cur = next;
        }

        return cur;
    }

Could not implement Bigdecimal in this for loop to get Fibonacci numbers

0

2 Answers 2

2

In your code, hasNext is always false. This tells the consumer of the iterator that we reached the end of the iteration.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

  1. As told by @Tom S. your hasNext method should return false if the count reaches to n.

  2. I changed logic in the next method. Take a look at it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.