2013-04-06 122 views
0

我想寫一個打印兩個笛卡兒乘積的Java程序。我用迭代器定義了兩個TreeSet。嵌套TreeSet迭代器 - Java

問題是,當我身邊這兩組使用聲明(嵌套的迭代),只有第二正在完成中所有元素。似乎迭代器正在彼此混淆。

while (iSet1.hasNext()) { // to iterate over the first set 
     int i = iSet1.next(); 

     while (iSet2.hasNext()) { // to iterate over the second set 
      int j = iSet2.next();    
      System.out.printf("(%d,%d)",i,j); 
     } // end of inner while 
    } // end of outer while 

如果SET1 = {1,2}和SET2 = {1,2}我得到這個輸出: (1,1)(1,2) 其中所希望的輸出是: (1,1)(1,2) (2,1),(2,2)

在此先感謝^ _^

+0

Flup have it right;在備註中,你應該真的將你的迭代器重命名爲有意義的東西 – BlackBox 2013-04-06 21:38:02

回答

2

如果要計算笛卡爾乘積,你會需要爲第一個迭代器的每個值重新初始化第二個迭代器。

while (iSet1.hasNext()) { // to iterate over the first set 
    int i = iSet1.next(); 
    iSet2 = secondSet.iterator(); // <- re-initialize the iterator here 
    while (iSet2.hasNext()) { // to iterate over the second set 
     int j = iSet2.next();    
     System.out.printf("(%d,%d)",i,j); 
    } // end of inner while 
} // end of outer while 
+0

太棒了!它只是工作^ _ ^謝謝 – 2013-04-06 21:49:57