我尝试了几种不同的方法。要求我使用继承来扩展这些类。每次我运行程序时,它的体积和面积就是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);
}
}
输出:
半径为30.0,面积为0.0,体积为0.0的圆柱体圆形
半径:50.0,面积0.0。半径为10.0,面积为0.0和
数量0.0
最佳答案
您的toString()
永远不会调用进行计算的方法,而是打印默认的0.0字段值。如果在调用toString()
方法之前(即在为计算字段指定适当值之前)调用过calcXxxx()
,您将冒此风险。最好的解决方案是,首先完全消除计算值的字段(例如面积和体积),以防止发生此问题。而是在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/