简体   繁体   中英

scope of variables when using for-loop in java - eclipse / compiler error?

I've written the following code:

for(int layer = 0; layer <countLayers; layer++);
{
    List<Sprite> spritesInLayer = sceneGraph.getLayer(layer);
}

when i compile this snippet, I get an error, that in the line within the for-Loop, eclipse complains that 'layer' is an unknown symbol [... = sceneGraph.getLayer(layer);] and wants me to introduce the field / variable / ... 'layer'.

But when using this snippet, it works.

int layer = 0;
for(layer = 0; layer <countLayers; layer++);
{
    List<Sprite> spritesInLayer = sceneGraph.getLayer(layer);
}

does anybody know, what I'm missing in the first code? Or might this be some kind of a bug of eclipse / the java compiler?

I'm using Java 6 JDK Update 20 64 bit on Win 7 64-bit Home Premium and Eclipse Helios 64-bit (build 20100617-1415)

Change

for(int layer = 0; layer <countLayers; layer++);

to

for(int layer = 0; layer <countLayers; layer++)

The spurious semicolon means that the for loop has an empty body. The following {....} is interpreted as a separate statement. And of course, layer is out of scope within that block.

delete the semicolon after the for line! The contents of the braces are not looped in your example, and therefore layer is undefined...

That's why eclipse is useful!

Please remove semicolon ";" from following line.

for(int layer = 0; layer < countLayers; layer++);

for statement doesn't require ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM