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

Luf*_*val 2 java processing arraylist

每当我尝试添加一个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);
Run Code Online (Sandbox Code Playgroud)

And*_*_CS 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

这将要求您Class在代码中更改您的姓名 - 请参阅下文.

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

    Country(int earth, int aqua, String yn)  {
        ......
Run Code Online (Sandbox Code Playgroud)

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

Country turkey = new Country(16, 7, "No");
Run Code Online (Sandbox Code Playgroud)

  • 在Processing中,这些实际上应该是`setup`方法,而不是main函数. (2认同)