简体   繁体   English

Double保持返回0.0

[英]Double keeps returning as 0.0

So my question is simple, I'm trying to implement method shapes and trying to print out the radius, area and volume of a sphere and cone. 所以我的问题很简单,我试图实现方法的形状,并试图打印出球体和圆锥体的半径,面积和体积。 Now I'm not asking for help with my homework, so bear with me. 现在,我不需要寻求家庭作业的帮助,所以请多多包涵。 Just some knowledge on why my double isn't putting out my intended variable. 关于为什么我的双胞胎没有给出预期变量的一些知识。

So at the moment all I'm trying to do is use a toString method to print "A " +name + " of radius " + r" 因此,目前我要尝试的是使用toString方法打印半径为“ + r”的“ A” +名称+“

which should just be "A sphere of radius 6.3" But instead when I run my program puts out "A sphere of radius 0.0" 它应该只是“半径为6.3的球体”,但是当我运行程序时,却输出了“半径为0.0的球体”

Heres my code: 这是我的代码:

//Main Class    
public class CircleShape
{
    String name;  
    double radius;
    double area;
    double volume;

    CircleShape(){
    }
        CircleShape(String n, double r, double a, double v)
    {
        name = n;
        radius = r;
        area = a;
        volume = v;
    } 
}

//Extension
public class SphereShape extends CircleShape
{
    public String name;
    public double r;


    public SphereShape(String n, double r)
    {
        name = n;
        radius = r;
    }

    public String getName(String name)
    {
        return name;
    }

    public void setName(String n)
    {
        name = n;
    }

    public double getRadius()
    {
        return radius;
    }

    public void setRadius(double r)
    {
    radius = r;
    }

    public String toString()
    {
    return "A " + name + " of radius " + r;
}


}
//Driver/Tester
public class CircleShapeTest extends CircleShape
{

    public static void main(String[] args)
    {
         SphereShape sph = new SphereShape("sphere", 6.3);


         System.out.println(sph);

   }
}

You never set the class var r , you are setting radius of CircleShape but never use this var. 您从未设置类var r ,而是设置了CircleShape radius ,但从未使用此var。

Change return "A " + name + " of radius " + r; 更改return "A " + name + " of radius " + r; to return "A " + name + " of radius " + radius ; return "A " + name + " of radius " + radius ;

Don't redeclare the same fields in subclasses. 不要在子类中重新声明相同的字段。 The four declarations in CircleShape are good enough and can be set and accessed by SphereShape . CircleShape中的四个声明足够好,可以由SphereShape设置和访问。 Recreating new fields is unnecessary and confusing and has caused your bug. 重新创建新字段是不必要且令人困惑的,并且已导致您的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM