Skip to content
Advertisement

why class Circle is not working in Java or I made any mistake, Please answer

I am trying to calculate the area of the circle using class and object in Java, but the output is not as I want. I want an answer as 78.5 but the area = 0.0, why? Here is the code below-

package com.company;
import java.util.Scanner;
class Circle{
    double r;
    double area= Math.PI*r*r;
}
public class practice {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        Circle c = new Circle();
        System.out.print("Enter the radius of circle: ");
        c.r = sc.nextDouble();
        System.out.println("The area of circle is: "+ c.area);
    }
}

The result I got is-

Enter the radius of circle: 5
The area of circle is: 0.0

Process finished with exit code 0

Advertisement

Answer

You have to understand that the code at the constructor will be run only once when an object is created.

If you have no constructor (like in your example code above) then the code will be run when the program is run. The values of not initialized double values will be 0.0. That’s the problem in your case too. Your area calculation will be translated to area = 3.14 * 0.0 * 0.0. I would suggest following the conventions and best practices this way:

     class Circle
    {
        private double radius = 0.0; // Best practice is to declare the variable private and access it through getters & setters

        public Circle(double radius)
        {
            this.radius = radius;
        }

        public double calculateArea()
        {
            return Math.PI * this.radius * this.radius ;
        }

        public double getRadius()
        {
            return radius;
        }

        public void setRadius(double radius)
        {
            this.radius = radius;
        }
    }

    public class Practice
    {
        public static void main(String[] args)
        {
            Circle c = new Circle(5);
            System.out.println("Area of this circle is : " + c.calculateArea());
        }
    }
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement