使用java计算体积和表面积

时间:2015-09-27 19:39:35

标签: java

我正在为我的Java I类开发一个项目。我已经包含了我写过的程序。我的公式似乎有效,但我的输出不是。这是项目 - “编写一个名为Sphere的类,其中包含表示球体直径的实例数据。定义球体构造函数以接受并初始化直径,并包括直径的getter和setter方法。包括计算和返回体积的体积和曲面的方法。包含一个toString方法,该方法返回球体的单行描述。创建一个名为Multisphere的驱动程序类,其主要方法是即时更新并更新多个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());
  }
}

2 个答案:

答案 0 :(得分:1)

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

这是你的家庭作业中的一个重要部分。没有提及球体的体积和表面积的任何内部状态,因此保持该值的字段值是没有意义的。您的方法是正确的,但您的toString应该只调用这些方法:

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

}

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

答案 1 :(得分:0)

private double calcVol;
private double calcSA;

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

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

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

同样在您的main()中,您在此行末尾还有d

Sphere sphere3 = new Sphere(8.0);d 
相关问题