[英]Design patterns: Iterator pattern
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;
}
無法在此 for 循環中實現 Bigdecimal 以獲取斐波那契數
在您的代碼中,hasNext 始終為 false。 這告訴迭代器的消費者我們已經到達迭代的結尾。
這就是你想要達到的
我用 Integer 替換了所有 BigDecimal 引用。 如果您想保持原樣,則需要進行一些小的更改。
//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
現在的重點是我做了什么改變。
正如@Tom S.所說,如果計數達到 n,您的 hasNext 方法應該返回 false。
我在下一個方法中更改了邏輯。 看看它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.