将常规Int转换为Final Java [英] Cast Regular Int to Final Java
问题描述
我正在尝试在一个循环中实现一个内部类,并且遇到了一种有趣的情况.内部类具有方法,但是,当我尝试访问该变量时,Netbeans会给我一个编译器错误,并告诉我将int设置为final.
I am trying to implement an inner class within a loop, and have come into an interesting situation. The internal class has methods, however, when I try and access the variable, Netbeans gives me a compiler error and tells me to make the int final.
由于int是一个循环变量,因此不能为最终变量.我尝试创建新变量并将它们等同于循环变量,但这仍然会引发相同的错误.
As the int is a looping variable, it can not be final. I have tried creating new variables and equating them to the looping variable, but this still throws the same error.
这是基本语法(用伪代码):
Here is the basic syntax (in pseudo-code):
for(int i = 0; i < 10; i++)
{
panels[i].printI(new printI(){System.out.println(i);});
}
有什么想法吗?
推荐答案
添加临时final
变量以保存值:
Add a temporary final
variable to hold the value:
for(int i = 0; i < 10; i++)
{
final int tmp = i;
panels[i].printI(new printI(){System.out.println(tmp);});
}
这篇关于将常规Int转换为Final Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!