gpt4 book ai didi

java - 使用java计算体积和表面积

转载 作者:行者123 更新时间:2023-12-01 11:07:15 25 4
gpt4 key购买 nike

我正在为我的 Java I 类(class)开发一个项目。我已经包含了我编写的程序。我的公式似乎有效,但我的输出却无效。这是该项目 - “编写一个名为 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 将始终代表最新的表面积和体积。

关于java - 使用java计算体积和表面积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32812076/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com