2016-03-17 70 views
-1

我想填補實踐問題上的空白。實現一個迭代

我已經完成了除最後一部分之外的所有部分,它們要求使用迭代器打印序列的前20個數字。我不確定什麼是最好的方法來做到這一點。

public class Duple implements Iterable{ 
    static Integer[] data = {1,7}; 

    public Iterator iterator(){ 
     _______return new MyIter();_____________ 
    } 
    private class MyIter implements Iterator{ 
     private int curr; 
     MyIter(){curr = 0;} 
      public boolean _____hasNext()_______{return true;} 
      public Object ___next()_________{ 
       Object o = data[curr]; 
       curr = (curr + 1) % data.length; 
       return o; 
      } 
      public void ____remove()____ { 
       throw new RuntimeException("don’t do this"); 
      } 
     }//end MyIter 
     public static void main(String[] args) { 
      //Declare a new Duple and its iterator. 
      ______Duple p = new Duple();__________ 
      ______p.iterator();___________________ 
     //Use the iterator to print the first twenty numbers of the 
     //sequence. You may not need every line. 
     ___________________________________ 
     ___________________________________ 
     ___________________________________ 
     ___________________________________ 
     ___________________________________ 
     } 
} 
+0

你必須做,'for'多次 –

回答

1

您可以使用一個for循環:

Duple p = ... 
Iterator iter = p.iterator(); 
for (int i = 0; i < 20 && iter.hasNext(); i++) 
    System.out.println(iter.next());