使用java计算体积和表面积



我正在为我的Java I类做一个项目。我已经把我写的程序写进去了。我的公式似乎是有效的,但我的输出不是。这个项目——"编写一个名为Sphere的类,其中包含代表球体直径的实例数据。定义球体构造函数来接受和初始化直径,并包含直径的getter和setter方法。包括计算和返回球体的体积和表面的方法。包括一个toString方法,它返回球体的一行描述。创建一个叫做Multisphere的驱动类,它的main方法实例化和更新几个Sphere对象。以下是我所写的:

public class Sphere 
{
  private double diameter;
  private double calcVol;
  private double calcSA;

  //----------------------------------------------------------------------------------------------
  //Constructor
  //----------------------------------------------------------------------------------------------
  public Sphere(double diameter)
  {
    this.diameter = diameter;
  }
  public void setDiameter(double diameter)
  {
    this.diameter = diameter;
  }
  public double getDiameter(double diameter)
  {
    return diameter;
  }
  public double calcVol()
  {
    return ((Math.PI) * (Math.pow(diameter, 3.0) / 6.0));   
  }
  public double calcSA()
  {
    return ((Math.PI) * Math.pow(diameter, 2.0));   
  }
  public String toString()
  {
    return "Diameter: " + diameter + " Volume: " + calcVol + " Surface Area: " + calcSA;
  }
}
public class MultiSphere 
{
  public static void main(String[] args) 
  {

    Sphere sphere1 = new Sphere(6.0);
    Sphere sphere2 = new Sphere(7.0);
    Sphere sphere3 = new Sphere(8.0);d

    sphere1.calcVol();
    sphere2.calcVol();
    sphere3.calcVol();
    sphere1.calcSA();
    sphere2.calcSA();
    sphere3.calcSA();
    System.out.println(sphere1.toString());
    System.out.println(sphere2.toString());
    System.out.println(sphere3.toString());
  }
}

包括计算和返回球体的体积和表面积的方法。

这是你们家庭作业中很重要的一行。这里没有提到球的体积和表面积的任何内部状态,所以保持场值是没有意义的。你的方法是正确的,但是你的toString应该只调用那些方法:

public String toString()
{
    return "Diameter: " + diameter + " Volume: " + calcVol() + " Surface Area: " + calcSA();
}

这样,您就不需要首先调用方法,并且如果直径发生变化,您的toString将始终表示最新的表面积和体积。

private double calcVol;
private double calcSA;

这些是你应该删除的行,你声明的新字段与你也有相同的方法名称。

toString中,你应该像这样调用你的方法

return "Diameter: " + diameter + " Volume: " + calcVol() + " Surface Area: " + calcSA();

同样在您的main()中您在这行末尾有一个额外的d

Sphere sphere3 = new Sphere(8.0);d 

最新更新