迭代器和 hasNext() 电源实现

iterator and hasNext() power implementation

我还在学习 java,我正在尝试实现一个迭代器接口,returns 整数的幂值(10^1 = 10、10^2 = 100 等)我在语法方面遇到了问题

首先,hasNext()方法一定不能改变"currentPow"成员的值。 正确的实施方式是:

@Override
  public boolean hasNext() {
  return currentPow <= maxPow;  
}

你一直得到相同结果 (10) 的原因是你没有乘以 class 的成员。 你真的不需要 "index" 成员,所以定义:

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();        
  }
}

迭代器中的变量不会每次都重置,您只是永远不要更新它们。所以在下一个运行他们是一样的

如前所述,您可能不应该在 hasNext() 内更新 currentPow。顾名思义,它只是检查是否有更多项目。然后,您应该转到 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;
  }