开发者

Yield in Python needs to be implemented in java

I have a following question:

Write a class that takes a series of integers from a generator that generates numbers one by one. Include two functions: 1- Sum 2- Average.

I know that yield statement is the choice in python if the generator needs to generate numbers one by one by returning at each step.

How would you guys do it in java? I somehow don't have any idea of how I 开发者_如何学JAVAcan realize this

Thanks.


if you want to implement "sequence" like behavior you may choose to implement java.util.Iterator interface.

class RandomSequence implements Iterator<Integer>, Iterable<Integer> {
     private int count;
     private Random random;


     public RandomSequence(int count) {
        this.count = count;
        this.random = new Random();
     }

     Integer next() {
        count--;

        return random.nextInt();

     }

     boolean hasNext() {
        return count > 0;
     }

     Iterator<Integer> iterator() {
        return this;
     }

     public static void main(String[] args) {
         int n = 0;
         for(int n: new RandomSequence(10))
             sum += n;
     }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜