无法添加到一个ArrayList"错位的构造(S)QUOT; [英] Can't add to an ArrayList "misplaced construct(s)"

查看:182
本文介绍了无法添加到一个ArrayList"错位的构造(S)QUOT;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的ArrayList成立,但我似乎无法将对象添加到它。

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)

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

任何人能解释为什么会这样?

Can anyone explain why this is happening?

推荐答案

为什么你的code不工作的原因是,你试着写code在类体内。可执行语句应该写在静态初始化,方法或构造函数(正如我在下面的例子一样)。

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).

试试这个:

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);
    }
}

我所定义的类成员广告资源在类体内和就地( =新的ArrayList()初始化它; )。没有编译器错误那里,因为声明允许类主体。在code我投入将初始化广告资源与值构造函数的其余部分。我可以把它放在一个方法,但我选择的构造,因为其通常的作用是初始化类成员。

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.

这篇关于无法添加到一个ArrayList"错位的构造(S)QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆