gpt4 book ai didi

java - 程序打印对于圆柱体面积、体积、范围+继承java保持打印0.0

转载 作者:行者123 更新时间:2023-12-01 18:02:00 25 4
gpt4 key购买 nike

我尝试了几种不同的方法。我需要使用继承来扩展这些类。每次我运行该程序时,它都会输出 0.0 的体积和面积。半径显示正确。输出在底部。

public class Base_HW04Q1
{
public double pi = 3.14, l, radius, height, area, volume;

public static class RoundShape extends Base_HW04Q1 {
public RoundShape(double radius) {
this.radius = radius;
}
public double calcArea () {
area = (radius * radius) * pi;
return area;
}
public String toString() {
return "A Round Shape of radius: " + radius + ", area " + area + ".";
}
}


public static class Cylinder extends Base_HW04Q1
{
public Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}
public double calcArea() {
l = Math.sqrt((radius * radius) + (height * height));
area = 2 * pi * radius * height + 2 * pi * l;
return area;
}
public double calcVolume() {
volume = pi * (radius * radius) * height;
return volume;
}
public String toString() {
return "A Cylinder of radius: " + radius + ", area " + area + " and a volume of " + volume;
}
}


public static class Cone extends Base_HW04Q1 //TODO: This line is almost, but not quite, complete.
{
public Cone(double radius, double height) {
this.radius = radius;
this.height = height;
}
public double calcArea() {
l = Math.sqrt((radius * radius) + (height * height));
area = (pi * radius * l) + (pi * radius * radius);
return area;
}
public double calcVolume() {
volume = 0.333 * pi * radius * radius * height;
return volume;
}
public String toString() {
return "A Cone of radius: " + radius + ", area " + area + " and a volume of " + volume;
}
}

public static void main(String[] args)
{
//object creation
Cylinder Cylinder1 = new Cylinder(30, 10);
Cone Cone1 = new Cone(10, 20);
RoundShape RoundShape1 = new RoundShape(50);

//print for objects
System.out.println(Cylinder1);
System.out.println(RoundShape1);
System.out.println(Cone1);
}
}

输出:

A Cylinder of radius: 30.0, area 0.0 and a volume of 0.0 A Round Shape of radius: 50.0, area 0.0. A Cone of radius: 10.0, area 0.0 and a volume of 0.0

最佳答案

您的 toString() 永远不会调用执行计算的方法,而是打印默认的 0.0 字段值。如果在调用 calcXxxx() 方法之前调用 toString(),您将面临此风险,即在计算字段被赋予适当的值之前。最好的解决方案是首先完全消除计算值(例如面积和体积)的字段,从而防止此问题发生。相反,在 toString() 中,调用方法来获取这些值。

例如,

public double pi = 3.14, l, radius, height; // , area, volume;

public static class RoundShape extends Base_HW04Q1 {
public RoundShape(double radius) {
this.radius = radius;
}
public double calcArea () {
return (radius * radius) * pi;
// return area;
}
public String toString() {
return "A Round Shape of radius: " + radius + ", area " + calcArea() + ".";
}
}

关于java - 程序打印对于圆柱体面积、体积、范围+继承java保持打印0.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40230438/

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