java: using default constructors in calculations

1.7k views Asked by At

I have to write a program using constructors which calculates the area of a circle using 5 methods:

Circle: The constructor that creates a circle with radius = 1

setRadius: takes an double argument and sets the radius to the argument

getRadius: returns an double argument with the value of the radius

computeDiameter: calculates the diameter and returns the value of the diameter

computeArea: calculates the area and returns the value of the area

So far, I reached here..

Main Class:

class MyClass{


        public static void main(String[] args) {

         MyClass1 circle= new MyClass1();

         System.out.println(circle.computeArea());          

        }

    }

This is the second class.. I haven't named it Circle though..

public class MyClass1 {

    private double radius;
    private double diameter;
    private double area;

    public MyClass1(){

        radius= 1.0;
    }

    public void setRadius(double radius){

        this.radius= radius;
    }

    public double getRadius(){

        return radius;
    }

    public double computeDiameter(){

        diameter= 2.0*radius;
        return diameter;
    }

    public double computeArea(){

        area= (Math.PI* Math.pow(diameter, 2))/4;
        return area;
    }

The problem is that the output for the area is giving me 0.0

3

There are 3 answers

0
Dmitry On BEST ANSWER

In constructor:

public MyClass1(){
    radius= 1.0;
}

diameter was not initialized. So it has value 0 set by default.

Your method:

public double computeArea(){
    area= (Math.PI* Math.pow(diameter, 2))/4;
    return area;
}

uses diameter parameter but it is zero at the moment it is used.

0
Manuel Jain On

your diamter is initially 0 and only gets set to the correct value after calling computeDiameter() , so try to replace area= (Math.PI* Math.pow(diameter, 2))/4; with area= (Math.PI* Math.pow(computeDiameter(), 2))/4;

0
Jullix993 On

Well you have not given diameter a value, so the diameter is 0.