我正在处理代码,但我遇到了这个问题。如何在下面提到的代码中使用for-each
执行与下面的循环显示相同的操作(两个嵌套for循环):
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
的情况下运行,我这样做只是为了满足我的好奇心。
答案 0 :(得分:2)
那么什么时候应该使用for-each循环?
任何时候你都可以。它真的美化了你的代码。不幸的是,你无法在任何地方使用它。例如,考虑一下expurgate方法。程序需要访问迭代器才能删除当前元素。 for-each循环隐藏了迭代器,因此您无法调用remove。因此,for-each循环不可用于过滤。类似地,它不适用于需要在遍历时替换列表或数组中的元素的循环。
答案 1 :(得分: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++;
}
}
答案 2 :(得分:0)
for (int[] row : result) {
for (int cell : row) {
// do something with the cell
}
}
但是由于您的代码需要行的行和单元格的索引,因此foreach循环不适合作业。保持您的代码不变。
你可以使用每个数组的长度而不是硬编码3。
答案 3 :(得分:0)
你可以在java中使用iterator,它对每个循环起作用 这是一个例子
// 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();
}
}
如果您有任何疑问,请联系