每当我尝试添加 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);
最佳答案
您需要将代码放入一个方法中 - 您可能想要使用 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 Country {
private int mland, mwaters; //mtotalborders;
private String mcenter;
Country(int earth, int aqua, String yn) {
......
此外,每当您引用Class
名称时。例如。
Country turkey = new Country(16, 7, "No");
关于java - 如何在处理过程中将类添加到数组列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24333044/