为什么我得到“从内部类引用的局部变量必须是最终的”? [英] Why am I getting "Local variables referenced from an inner class must be final"?

查看:208
本文介绍了为什么我得到“从内部类引用的局部变量必须是最终的”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我甚至不确定这段代码是否会做任何事情,即使它有效,但我不知道如何摆脱从内部类引用的局部变量必须是最终的或有效的最终错误消息,显示在以fireballRight [i]开头的三行上。

I'm not even sure if this code will do anything even if it works, but I don't know what to do to get rid of the "Local variables referenced from an inner class must be final or effectively final" error message, which shows up on the three lines that start with "fireballRight[i]".

Sprite[] fireballRight = new Sprite[50];

public void fireRight() {

    for(int i = 0; i < 50; i++) {
        new AnimationTimer() {
            public void handle() {      

                fireballRight[i].setImage("puercosloco/fireballright.png");                   

                rightx++;
                fireballRight[i].setPosition(rightx, righty);
                fireballRight[i].render(gc, 80, 55);           
            }
        }.start();     
    }   
}

任何指导都会受到赞赏,google看起来似乎不大帮助我这个。

Any guidance would be appreciated, google doesn't seem to be helping me for this one.

推荐答案

您没有显示所有代码,但我怀疑添加:

You haven't shown all the code, but I suspect that adding:

final int i0 = i;

在你的循环中并使用 i0 而不是 i 因为数组的索引应该修复错误。

inside your loop and using i0 instead of i as the index for your arrays should fix the error.

或者,如@James_D所评论,你可以在匿名类之前添加 Sprite sprite = fireballRight [i]; 并在 sprite > handle 方法。

Alternatively, as commented by @James_D, you can also add Sprite sprite = fireballRight[i]; before the anonymous class and use sprite inside the handle method.

注意 final 修饰符在这种情况下是可选的Java 8 +。

Note that the final modifier is optional in this case with Java 8+.

这篇关于为什么我得到“从内部类引用的局部变量必须是最终的”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆