java计算人口密度:初学者指南
好吧,我对这个还是很陌生,我不知道我的代码是怎么回事。它看起来是对的,但是当我试着运行它时,它给了我一个零除的错误
代码1在老师给我的一页上:
public class Country
{
// fields
private String name;
private int population;
private int area; // in square miles
// constructors
// methods
public String getName()
{
return name;
}
public int getPopulation()
{
return population;
}
public int getArea()
{
return area;
}
public void setName(String newName)
{
name = newName;
}
public void setPopulation(int newPopulation)
{
population = newPopulation;
}
public void setArea(int newArea)
{
area = newArea;
}
// population per square mile
public int populationDensity()
{
int density;
density = population / area; // integer division truncates
return density;
}
}
还有一个我做过的:
public class A03
{
public static void main(String[] args)
{
Country country1 = new Country();
String newName = "Macau";
int newPopulation = 453000;
int newArea = 6;
int density = newPopulation / newArea;
country1.setName(newName);
country1.setPopulation(newPopulation);
country1.setArea(newArea);
System.out.printf("Name: " + country1.getName());
System.out.printf("%nPopulation: %,d ", country1.getPopulation());
System.out.printf("%nArea: "+ country1.getArea());
System.out.printf("%nPopulation Density: %,d", country1.populationDensity(), "%n");
System.out.println();
System.out.println();
Country country2 = new Country();
String name1 = "Libya";
int population1 = 5900000;
int area1 = 679358;
int density1 = population1 / area1;
System.out.printf("Name: %s%n", name1);
System.out.printf("Population: %,d%n", population1);
System.out.printf("Area: %,d%n", area1);
System.out.printf("Population Density: %,d%", country2.populationDensity(), "%n");
System.out.println();
Country country3 = new Country();
String name2 = "USA";
int population2 = 298500000;
int area2 = 3539225;
int density2 = population2 / area2;
System.out.printf("Name: %s%n", name2);
System.out.printf("Population: %,d%n", population2);
System.out.printf("Area: %,d%n", area2);
System.out.println();
}
}
有人能告诉我怎么了吗?或者我所做的是错的。我基本上复制、粘贴和更改了我的变量,以适应下一个国家的人口密度
# 1 楼答案
在
main
中,您没有在country2
或country3
上调用任何setter方法。您只声明了变量。当实例变量没有赋值时,Java会指定默认值,对于基本数字类型,默认值为0
。这就解释了为什么会有被零除的错误调用
country2
和country3
的setter(和getter)# 2 楼答案
您没有设置country2对象的人口和面积属性以及调用时间
你除以零是因为:在populationDensity()中,你除以面积,它没有设置,所以它是0