每当我尝试在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);
答案 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,您正试图在类定义之外编写代码。全局变量声明是可以的,可执行语句不是。