如何在处理中向一个arraylist添加一个类?

时间:2014-06-20 17:54:42

标签: java arraylist processing

每当我尝试在country中添加ArrayList<country>时,我都会收到此错误:unexpected token: (并突出显示我的countries.add行。我不确定为什么会这样。

class country  {
    private int mland, mwaters; //mtotalborders;
    private String mcenter;

    country(int earth, int aqua, String yn)  {
        mland = earth;
        mwaters = aqua;
        mcenter = yn;
    }
    public int getLand()  {
        return mland;
    }
    public int getWaters()  {
        return mwaters;
    }
    public int getTotalBorders()  {
        return mland+mwaters;
    }
    public String getCenter()  {
        return mcenter;
    }
}

country Turkey = new country(16, 7, "No");
country France = new country(22, 4, "No");
country England = new country(17, 9, "No");
country Germany = new country(26, 4, "Yes");
country Austria = new country(28, 1, "Yes");
country Italy = new country(17, 8, "Yes");
country Russia = new country(23, 3, "No");
ArrayList<country> countries = new ArrayList<country>();
countries.add(Turkey);

2 个答案:

答案 0 :(得分:6)

您需要将代码放入方法中 - 您可能希望使用main方法 - 请参阅下文。

    ......

    public String getCenter()  {
        return mcenter;
    }

    public static void main(String[] args){
        country Turkey = new country(16, 7, "No");
        country France = new country(22, 4, "No");
        country England = new country(17, 9, "No");
        country Germany = new country(26, 4, "Yes");
        country Austria = new country(28, 1, "Yes");
        country Italy = new country(17, 8, "Yes");
        country Russia = new country(23, 3, "No");
        ArrayList<country> countries = new ArrayList<country>();
        countries.add(Turkey);
    }
}

注意:正确的约定是大写Class名称,并将变量名称设为小写。

这将要求您更改代码中的Class名称 - 请参阅下文。

class Country  {
    private int mland, mwaters; //mtotalborders;
    private String mcenter;

    Country(int earth, int aqua, String yn)  {
        ......

您也可以随时引用Class名称。例如。

Country turkey = new Country(16, 7, "No");

答案 1 :(得分:1)

Lufval,您正试图在类定义之外编写代码。全局变量声明是可以的,可执行语句不是。

相关问题