我尝试了几种不同的方法。我需要使用继承来扩展这些类。每次我运行程序时,它只会输出0.0的体积和面积。半径显示正确。输出在底部。
get '/player/:playerId' => 'players#show'
get '/player/:playerId/edit' => 'players#edit'
输出:
圆柱半径:30.0,面积0.0,体积为0.0圆形 半径:50.0,面积0.0。半径锥:10.0,面积0.0和a 体积为0.0
答案 0 :(得分:4)
您的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() + ".";
}
}
答案 1 :(得分:0)
这是因为你只是实例化对象并输入到构造函数而不是其他方法。
Cylinder Cylinder1 = new Cylinder(30, 10);
Cone Cone1 = new Cone(10, 20);
RoundShape RoundShape1 = new RoundShape(50);
没有人打电话给这些方法
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;
}
和其他方法。如果您想通过以下方法计算,请从构造函数或main中调用它们:
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);
double roundArea = RoundShape1.calcArea();//then use this
string roundMessage = RoundShape1.toString();//and this whatever you want.
//do it in others too
//print for objects
System.out.println(Cylinder1);
System.out.println(RoundShape1);
System.out.println(Cone1);
}