Why am I getting “Local variables referenced from an inner class must be final”?

后端 未结 3 1556
礼貌的吻别
礼貌的吻别 2021-01-27 09:26

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

相关标签:
3条回答
  • 2021-01-27 09:44

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

    final int i0 = i;
    

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

    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.

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

    0 讨论(0)
  • 2021-01-27 09:53

    As it says, the var i needs to have the final prefix. Change the code to something like this:-

        for(int i = 0; i < 50; i++) {
            final int i2 = i;
            new AnimationTimer()
            {
                public void handle()
                {      
                    fireballRight[i2].setImage("puercosloco/fireballright.png"); // Use i2 instead of i.
    
    0 讨论(0)
  • 2021-01-27 09:55

    You can do the field private and static.

    0 讨论(0)
提交回复
热议问题