I was working on a code and I came across this. How can I use for-each in the below mentioned code to perform the same as the loop show exactly below (two nested for loops):
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) makes i an array, then would it be possible to use for-each in this case?
PS:I have got my code working without using for-each, i am asking this just to satisfy my curiosity.
From the Sun Java Docs:
So when should you use the for-each loop?
Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it.