Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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() + "
"; 

        return report;
    }
}  

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
571 views
Welcome To Ask or Share your Answers For Others

1 Answer

count++; will throw an error. Per 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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...