2011-12-25 125 views
1

我正在編寫代碼,並且遇到了這個問題。如何使用for-each在下文提到的代碼,以執行相同的循環顯示恰好低於(兩個嵌套的for循環):如何在這種情況下用java替換foreach循環(在java中)?

String names[3] = {"A","B","C"}; 
int result[][] = calculate_exchange(calculate_matrix());//function call returns a 3x3 matrix 
     /*for(int i[]:result){ 
      for(int j:i){ 
       if(j!=0){ 
        System.out.println(names[]);//how do I use the i'th element? 
        //names[i] gives an error(obviously!!!) 
       } 
      } 
     }*/ 
     for(int r=0;r<3;r++){//this loop works fine 
      for(int c=0;c<3;c++){ 
       if(result[r][c]!=0){ 
        System.out.println(names[r]+"->"+names[c]+" = "+result[r][c]); 
       } 
      } 
     } 

for(int i[]:result)使得i陣列,這樣纔有可能在此使用for-each案件?

PS:我有我的代碼工作沒有使用for-each,我問這只是爲了滿足我的好奇心。

回答

2

Sun Java Docs

所以,當你應該使用for-each循環?

任何時候都可以。它真的美化你的代碼。不幸的是,你無法在任何地方使用它。例如,考慮expurgate方法。該程序需要訪問迭代器才能刪除當前元素。 for-each循環隱藏了迭代器,所以你不能調用remove。因此,for-each循環不能用於過濾。同樣,它不適用於需要在遍歷列表或數組時替換元素的循環。

0
for (int[] row : result) { 
    for (int cell : row) { 
     // do something with the cell 
    } 
} 

但你的代碼需要的行和列的單元格的指數,foreach循環是不爲工作的工具。保持你的代碼不變。

你可以只使用每個數組的長度,而不是硬編碼3.

+0

我有我的代碼工作,我問這只是因爲我很好奇。 – buch11 2011-12-25 13:52:16

+1

當您不關心索引時,foreach循環很有用。你的代碼需要使用索引。你可以聲明兩個索引變量,但是你的代碼與原代碼相似,但可讀性較差。見Peter Lawrey的答案。其他每一個答案都和我的一樣,不是正確的工具。我認爲我的回答不值得讚揚。 – 2011-12-25 13:57:12

+0

好吧,我得到的東西,感謝您的幫助。 – buch11 2011-12-25 13:59:42

1

在這種情況下,您不能做一個乾淨的替換,因爲在循環中使用c。 (所以你不能完全消除)

你可以寫

for(int r=0,c;r<3;r++){//this loop works fine 
    c=0; 
    for(int[] row: result[r]){ 
     if(row[c]!=0) 
     System.out.println(names[r]+"->"+names[c]+" = "+row[c]); 
     c++; 
    } 
} 
+0

但是沒有人在他們的正確思想中這樣寫代碼。正如JB Nezbit指出的那樣,「每個」循環對於這項工作來說都是錯誤的工具。 – 2011-12-25 15:03:00

0

您可以在Java中使用迭代器,其作用就像每個循環 這裏是一個例子

// Demonstrate iterators. 
import java.util.*; 
class IteratorDemo { 
public static void main(String args[]) { 
// create an array list 
ArrayList al = new ArrayList(); 
// add elements to the array list 
al.add("C"); 
al.add("A"); 
al.add("E"); 
al.add("B"); 
al.add("D"); 
al.add("F"); 
// use iterator to display contents of al 
System.out.print("Original contents of al: "); 
Iterator itr = al.iterator(); 
while(itr.hasNext()) { 

Object element = itr.next(); 
System.out.print(element + " "); 

} 
System.out.println(); 
// modify objects being iterated 
ListIterator litr = al.listIterator(); 
while(litr.hasNext()) { 

Object element = litr.next(); 
litr.set(element + "+"); 

} 
System.out.print("Modified contents of al: "); 
itr = al.iterator(); 
while(itr.hasNext()) { 

Object element = itr.next(); 
System.out.print(element + " "); 

} 
System.out.println(); 
// now, display the list backwards 
System.out.print("Modified list backwards: "); 
while(litr.hasPrevious()) { 

Object element = litr.previous(); 
System.out.print(element + " "); 

} 
System.out.println(); 
} 
} 

聯繫如果u有任何疑問

相關問題