jeudi 14 mai 2020

Design patterns: Iterator pattern

import java.math.BigDecimal;
import java.util.Iterator;

public class IteratorPattern {

    public static void main(String[] args) {

        int n = 100;
        FibonacciSequence fibonacciSequence = new FibonacciSequence(n);

        //iteration using iterator for-loop

        for (BigDecimal fibonacciNumber : fibonacciSequence) {
            System.out.println(fibonacciNumber);
        }

        System.out.println();

        //iteration using iterator

        Iterator<BigDecimal> iterator = fibonacciSequence.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
    }
}

Implementation of "FibonacciSequence" class

class FibonacciSequence implements Iterable<BigDecimal>, Iterator<BigDecimal> 
{
    private final int n;

    FibonacciSequence(int n) {
        this.n = n;
    }

    @Override
    public boolean hasNext() {
        return false;
    }

    @Override
    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;
    }

    @Override
    public Iterator<BigDecimal> iterator() {
        return new FibonacciSequence(n);
    }

}

I want to print Fibonacci series both using for loop and iterator pattern. But I was not able to get any output. İt does nit give error too. Where might i be wrong? What is i am missing?

Aucun commentaire:

Enregistrer un commentaire