我想打印出国家名称及其分类(如代码末尾所示)。但是,if语句不起作用。我尝试将它从构造函数中删除,但这不起作用,当我在我的main方法中尝试它时无论如何都不会工作,因为变量是在类Country中定义的。所以我想问一下,我如何使用这个if语句进行分类。
public class Exercise {
public static void main(String[] args){
Country Sweden = new Country("Sweden", 498000000000l,10000000);
Sweden.representcountry();
}
public static class Country{
String name;
long GDP;
int population;
int GDPCapita;
String classification;
public Country(String name, long GDP, int population){
this.name = name;
this.GDP = GDP;
this.population = population;
GDPCapita = (int) (this.GDP / this.population);
}
// Getters and Setters
/*
if(GDPCapita >= 10000){
classification = "Developed country";
}
else {
classification = "Developing country";
}
*/
final String END_OF_LINE = System.lineSeparator();
public String representcountry(){
System.out.println(this.name + ":" + END_OF_LINE // + classification
+ "Population: " + + this.population + END_OF_LINE
+ "GDP: " + this.GDP + END_OF_LINE
+ GDPCapita + " per capita");
return "";
}
}
}
答案 0 :(得分:4)
你这样做:
public Country(String name, long GDP, int population){
this.name = name;
this.GDP = GDP;
this.population = population;
GDPCapita = (int) (this.GDP / this.population);
if(GDPCapita >= 10000){
classification = "Developed country";
}else {
classification = "Developing country";
}
}
通过使用三元运算符你可以替换if / else,他更短,但你需要理解并喜欢它,这只是一个提示:
classification = GDPCapita >= 10000 ? "Developed country" : "Developing country";
答案 1 :(得分:1)
为什么你在任何地方使用关键字" this。"除了GDPCapita和分类?
public Country(String name, long GDP, int population){
// Getters and Setters
this.name = name;
this.GDP = GDP;
this.population = population;
this.GDPCapita = (int) (this.GDP / this.population);
if(this.GDPCapita >= 10000){
this.classification = "Developed country";
}
else {
this.classification = "Developing country";
}
}