求教Java编程思想里面的一题,怎么也找不到错误在哪!

privilege1900 privilege1900 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
这是书上第11章持有对象里面的练习31题
(3)修改RandomShapeGenerator.java,使其成为一个Iterable。
这是LZ写的代码:

public class RandomShapeIterable implements Iterator<Shape> {
private Random rand = new Random(27);
private final int generateShapeNum;
public RandomShapeIterable( int generateShapeNum ) {
this.generateShapeNum = generateShapeNum;
}

public Iterator<Shape> iterator() {
return new Iterator<Shape>() {
private int num = 0;
public boolean hasNext() {
return num < generateShapeNum;
}
public Shape next() {
num++;
switch(rand.nextInt(3)) {
default:
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
for (Shape s : new RandomShapeIterable(10)) {
s.draw();
s.erase();
}
}

}


报错如下:


在下面是答案上的代码
class RandomShapeGenerator implements Iterable<Shape> {
private Random rand = new Random(47);
private final int quantity;

RandomShapeGenerator(int quantity) {
this.quantity = quantity;
}

public Iterator<Shape> iterator() {
return new Iterator<Shape>() {
private int count;

public boolean hasNext() {
return count < quantity;
}

public Shape next() {
++count;
return nextShape();
}

public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
};
}

private Shape nextShape() {
switch (rand.nextInt(3)) {
default:
case 0:
return new Circle();
case 1:
return new Square();
case 2:
return new Triangle();
}
}
}

public class E31_IterableRandomShapeGenerator {
public static void main(String[] args) {
RandomShapeGenerator rsg = new RandomShapeGenerator(10);
for (Shape shape : rsg)
System.out.println(shape.getClass().getSimpleName());
}
}


好吧,撸主不明白的地方有两处:
一、为什么实现Iterable接口的类不用在类中实现hasNext()、next()、remove()的定义,
然而在内部类里实现后却能够运行?
二、撸主检查了一遍又一遍实在是找不到自己写的代码到底哪里出了错,我感觉明明就跟答案里的一样啊?
跪求大神指点啊!!!
...全文

相关推荐

评论 6
收藏 已收藏
分享
返回顶部
privilege1900
Java SE 62,620 成员 307,251 内容