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

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

java - Can't add to an ArrayList "misplaced construct(s)"

I have a simple arraylist set up, but I can't seem to add objects to it.

import java.util.ArrayList;


public class Inventory {

ArrayList inventory = new ArrayList();

String item1 = "Sword";
String item2 = "Potion";
String item3 = "Shield";

inventory.add(item1);
inventory.add(item2);
inventory.add(item3);
}

There are two errors, one at the dot between inventory and add, and one at the variable names between the brackets, being

Syntax error on token(s), misplaced construct(s)

and

Syntax error on token "item1", VariableDeclaratorId expected after this token

Can anyone explain why this is happening?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The reason why your code does not work is that you tried to write code in the class body. Executable statements should be written in static initializers, methods or constructors (as I did in the example below).

Try this:

public class Inventory {

    private List inventory = new ArrayList();

    public Inventory() {

        String item1 = "Sword";
        String item2 = "Potion";
        String item3 = "Shield";

        inventory.add(item1);
        inventory.add(item2);
        inventory.add(item3);
    }
}

I defined the class member inventory in the class body and initialized it in-place (= new ArrayList();). No compiler error there because declarations are allowed in class body. The rest of the code I put into the constructor that will initialize inventory with values. I could have put it in a method, but I chose the constructor because its usual role is to initialize class members.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...