错误:无法为最终变量赋值 [英] error: cannot assign a value to final variable
问题描述
我正在处理一项任务,我遇到了这个错误:无法为最终变量计数分配值
I am working on an assignment and I'm stuck on this error: cannot assign a value to final variable count
这是我的代码到目前为止...
Here is my code so far...
public class List
{
private final int Max = 25;
private final int count;
private Person list[];
public List()
{
count = 0;
list = new Person[Max];
}
public void addSomeone(Person p)
{
if (count < Max){
count++; // THIS IS WHERE THE ERROR OCCURS
list[count-1] = p;
}
}
public String toString()
{
String report = "";
for (int x=0; x < count; x++)
report += list[x].toString() + "\n";
return report;
}
}
我对java很新,显然不是计算机高手,请用最简单的术语解释问题/解决方案。非常感谢你。
I'm very new to java and am obviously not a computer whiz so please explain the problem/solution in the simplest terms possible. Thank you so much.
推荐答案
count ++;
会抛出错误。每个Oracle,
count++;
will throw an error. Per Oracle,
最终变量只能分配一次。声明变量final可以作为有用的文档,它的值不会改变,可以帮助避免编程错误。
A final variable may only be assigned to once. Declaring a variable final can serve as useful documentation that its value will not change and can help avoid programming errors.
你可以跟随该文章此处 。看看你的代码,你似乎真的不希望 count
成为最终版。您希望能够在整个程序中更改其值。解决方法是删除 final
修饰符。
You can follow along with that article here. Looking at your code, it seems that you really don't want count
to be final. You want to be able to change its value throughout the program. The fix would be to remove the final
modifier.
这篇关于错误:无法为最终变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!