简体   繁体   中英

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"

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"

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.

Change return "A " + name + " of radius " + r; to 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 . Recreating new fields is unnecessary and confusing and has caused your bug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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