where to define variable for a for each loop?
- by David
can you please advise me why my first code attempt didn't work :
public void listAllFiles()
{
for(String filename : files)
{
int position = 0;
System.out.println(position + ": " + filename);
position = position + 1;
}
}
it kept printing position at 0 without iterating position
but it seems to work after i did it this way:
public void listAllFiles()
{
int position = 0;
for(String filename : files)
{
System.out.println(position + ": " + filename);
position = position + 1;
}
}
I don't understand why the position + 1 was not being executed, is it because we are not meant to define variables inside for loops or am i missing something in my code.