我还在学习java,我正在尝试实现一个迭代器接口,它返回整数的幂值(10^1 = 10,10^2 = 100等),语法也有问题。
发布于 2017-03-28 18:59:42
首先,hasNext()方法不能更改"currentPow“成员的值。正确的执行办法是:
@Override
public boolean hasNext() {
return currentPow <= maxPow;
}您一直获得相同结果(10)的原因是,您没有将类中的一个成员相乘。您不需要真正的“索引”成员,所以应该定义:
public class powIterator implements Iterator<Integer>{
private int currentPow = 1;
private int currentResult = 1; 现在,next()应该如下所示:
@Override
public Integer next() throws NoSuchElementException {
if (index <= maxPow){
index++;
currentResult *= base;
return currentResult;
}
else {
throw new NoSuchElementException();
}
}发布于 2017-03-28 19:12:24
Iterator中的变量不是每次都会被重置,您根本就不会更新它们。所以在下一轮比赛中,他们是一样的。
如前所述,您可能不应该在currentPow中更新hasNext()。顾名思义,这只是一个检查是否有更多的项目。然后,您应该移到next()中的下一个步骤。
也许可以试试这样的方法:
private int currentPow = 1;
@Override
public boolean hasNext() {
return currentPow <= maxPow;
}
@Override
public Integer next() throws NoSuchElementException {
if(currentPow > maxPow)
throw new NoSuchElementException("Power is above the maximum");
int pow = (int) Math.pow(base, currentPow);
currentPow++;
return pow;
}https://stackoverflow.com/questions/43077308
复制相似问题