计算人口密度:初学者指南

时间:2015-02-05 20:56:24

标签: 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();

   }
}

有人可以告诉我有什么问题吗?或者我做错了什么。我基本上复制,粘贴和更改了我的变量,以适应​​下一个国家的人口密度。

2 个答案:

答案 0 :(得分:4)

main中,您未在country2country3上调用任何setter方法。您只声明了变量。如果没有为实例变量赋值,Java会为原始数字类型指定默认值0。这就解释了为什么你有零除错误。

country2country3打电话给您的二传手(和吸气员)。

答案 1 :(得分:0)

您没有设置country2对象的种群和区域属性以及调用时

      System.out.printf("Population Density: %,d%", country2.populationDensity(),   "%n");

你除以零是因为:在populationDensity()中,你除以区域而没有设置,所以它是0。