简体   繁体   English

在Java中使用for循环时的变量范围-Eclipse /编译器错误?

[英]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'. 当我编译此代码段时,出现一个错误,在for-Loop内的行中,eclipse抱怨'layer'是一个未知符号[... = sceneGraph.getLayer(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? 还是这可能是Eclipse / Java编译器的某种错误?

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) 我在Win 7 64位家庭高级版和Eclipse Helios 64位(内部版本20100617-1415)上使用Java 6 JDK Update 20 64位

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. 虚假的分号表示for循环的主体为空。 The following {....} is interpreted as a separate statement. 以下{....}被解释为单独的语句。 And of course, layer is out of scope within that block. 当然,该layer不在范围之内。

delete the semicolon after the for line! for行后删除分号! The contents of the braces are not looped in your example, and therefore layer is undefined... 在您的示例中,括号的内容未循环,因此layer未定义...

That's why eclipse is useful! 这就是为什么月食有用的原因!

Please remove semicolon ";" 请删除分号“;” from following line. 从下面一行。

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

for statement doesn't require ; 不需要声明;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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