buch11
buch11

Reputation: 882

how to replace for loops with foreach in this case(in java)?

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.

Upvotes: 1

Views: 2245

Answers (4)

Zlatan
Zlatan

Reputation: 698

You can use iterator in java which act like for each loop here's an example

// 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(); 
} 
}

Contact if u have any doubt

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533500

In this case you can't do a clean replacement because c is used in the loop. (so you can't eliminate it completely)

You can write

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++;
   }
 }

Upvotes: 1

Shadow
Shadow

Reputation: 6277

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.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691715

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

But since your code needs the index of the row and of the cell in the row, the foreach loop is just not the right tool for the job. Keep your code as is.

You could just use the length of each array rather than hardcoding 3.

Upvotes: 0

Related Questions