Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class FibSequence {
- public static class FibIterator {
- private int current;
- private int limit;
- private int nextfib;
- private int lastfib;
- public FibIterator(int theLimit) {
- limit = theLimit;
- current = 0;
- lastfib = 1;
- nextfib = 2;
- }
- public void first() {}
- public int currentItem() {
- return(lastfib);
- }
- public void next() {
- int temp;
- switch(current) {
- case 0:
- case 1:
- current += 1;
- default:
- current += 1;
- temp = nextfib;
- nextfib += lastfib;
- lastfib = temp;
- }
- }
- public boolean isDone() {
- return(current == limit);
- }
- }
- public FibIterator createIterator(int theLimit) {
- return new FibIterator(theLimit);
- }
- }
- /* Use the iterator to cycle thru first 6 elements */
- FibSequence f = new FibSequence();
- FibIterator fi = f.createIterator(6);
- for (fi.first(); !fi.isDone(); fi.next()) {
- System.out.print( fi.currentItem() + ":");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement