where to define variable for a for each loop?
Posted
by
David
on Programmers
See other posts from Programmers
or by David
Published on 2014-06-01T12:17:52Z
Indexed on
2014/06/01
15:51 UTC
Read the original article
Hit count: 280
java
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.
© Programmers or respective owner