Advertisement
saasbook

fib.java

Jan 10th, 2012
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class FibSequence {
  4. public static class FibIterator {
  5. private int current;
  6. private int limit;
  7. private int nextfib;
  8. private int lastfib;
  9. public FibIterator(int theLimit) {
  10. limit = theLimit;
  11. current = 0;
  12. lastfib = 1;
  13. nextfib = 2;
  14. }
  15. public void first() {}
  16. public int currentItem() {
  17. return(lastfib);
  18. }
  19. public void next() {
  20. int temp;
  21. switch(current) {
  22. case 0:
  23. case 1:
  24. current += 1;
  25. default:
  26. current += 1;
  27. temp = nextfib;
  28. nextfib += lastfib;
  29. lastfib = temp;
  30. }
  31. }
  32. public boolean isDone() {
  33. return(current == limit);
  34. }
  35. }
  36. public FibIterator createIterator(int theLimit) {
  37. return new FibIterator(theLimit);
  38. }
  39. }
  40.  
  41. /* Use the iterator to cycle thru first 6 elements */
  42.  
  43. FibSequence f = new FibSequence();
  44. FibIterator fi = f.createIterator(6);
  45. for (fi.first(); !fi.isDone(); fi.next()) {
  46. System.out.print( fi.currentItem() + ":");
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement