我正在做一个赋值,但我遇到了这个错误:无法为最终变量计数赋值
到目前为止,这是我的代码...
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 的新手,显然不是计算机高手,所以请尽可能用最简单的术语解释问题/解决方案。非常感谢。
最佳答案
count++;
会抛出错误。根据 Oracle,
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.
您可以跟随那篇文章here .查看您的代码,您似乎真的不希望 count
成为最终的。您希望能够在整个程序中更改其值。解决方法是删除 final
修饰符。
关于java - 错误 : cannot assign a value to final variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32791995/