public class Country {
public static void main(String[] args) {
String country_name;
String capital;
String iso_numeric;
String iso2;
String iso3;
String[] name = new String[] {"united_state", "united_kingdom", "france", "germany", "canada"};
for(int i = 0; i < name.length; i++) {
Country name[i] = new Country();
}
}
}
嗨,我有上面的代码:
我想要做的是自动创建Country类的对象引用,所以到最后我应该有类似的东西:
Country united_state = new Country();
Country united_kingdom = new Country();
Country france = new Country();
Country germany = new Country();
Country canada = new Country();
但是,我收到的错误是: 国家名称[i] =新国家();
提前感谢您的时间和帮助。
答案 0 :(得分:0)
您似乎想要这个:
public class Country {
private final String name;
// Add these later
// private final String capital;
// private final String iso_numeric;
// private final String iso2;
// private final String iso3;
public Country(String name) {
this.name = name;
}
public String getName() { return this.name; }
}
有了这个,你可以这样做:
String[] name = new String[] {"united_state", "united_kingdom", "france", "germany", "canada"};
List<Country> countries = new ArrayList<Country>();
for(int i = 0; i < name.length; i++) {
countries.add(new Country(name[i]));
}
答案 1 :(得分:0)
在我看来,你想要的是一个枚举:
public enum Country {
united_states("United States", "Washington", "840", "us", "usa"),
united_kingdom("United Kingdom", "London", (* etc */)),
france(/* etc */),
germany(/* etc */),
canada(/* etc */);
String country_name;
String capital;
String iso_numeric;
String iso2;
String iso3;
private Country(String country_name, String capital, String iso_numeric, String iso2, String iso3) {
this.country_name = country_name;
this.capital = capital;
this.iso_numeric = iso_numeric;
this.iso2 = iso2;
this.iso3 = iso3;
}
}
要获取所有国家/地区的数组,请使用Country.values()
。请阅读有关Java枚举的教程以了解更多信息。