Circle class program

The problem

Write a Circle class that has the following fields:

  • radius: a double
  • PI: a final double initialized with the value 3.14159

The class should have the following methods:

  • Constructor. accepts the radius of the circle as an argument.
  • Constructor. A no-arg constructor that sets the radius field to 0.0.
  • setRadius. A mutator method for the radius field.
  • getRadius. An accessor method for the radius field.
  • getArea. Returns the area of the circle which is calculated as * area=PIradiusradius
  • getDiameter. Returns the diameter of the circle which is calculated as diameter=radius*2
  • getCircumference. Returns the circumference of the circle, which is calculated as circumference= 2PIradius

Write a program that demonstrates the Circle class by asking the user for the circle's radius, creating a Circle object, and then reporting the circle's area, diameter, and circumference.

Breaking it down

Create circle class

public class Circle {

    private final double PI = 3.14159;
    private double radius;

    public Circle() {
        radius = 0.0;
    }

    public Circle(double r) {
        radius = r;
    }

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

    public double getRadius() {
        return radius;
    }

    public double getArea() {
        return PI * radius * radius;
    }

    public double getDiameter() {
        return radius * 2;
    }

    public double getCircumference() {
        return 2 * PI * radius;
    }
}

Create program

public static void main(String[] args) {

    // Create a Scanner object for keyboard input.
    Scanner keyboard = new Scanner(System.in);

    // Ask user to input circle radius
    System.out.print("Enter the radius of a circle: ");
    double radius = keyboard.nextDouble();

    // close keyboard
    keyboard.close();

    // Create a Circle object passing in user input
    CircleClass circleClass = new CircleClass();
    Circle circle = circleClass.new Circle(radius);

    // Display circle information
    System.out.println("Area is " + circle.getArea());
    System.out.println("Diameter is " + circle.getDiameter());
    System.out.println("Circumference is " + circle.getCircumference());

}

Output

Enter the radius of a circle: 10.5
Area is 346.3602975
Diameter is 21.0
Circumference is 65.97339

Unit tests

@Test
public void test_getArea() {

    CircleClass circleClass = new CircleClass();
    Circle circle = circleClass.new Circle(10);

    assertEquals(314.159, circle.getArea(), 0);
}

@Test
public void test_getDiameter() {

    CircleClass circleClass = new CircleClass();
    Circle circle = circleClass.new Circle(10);

    assertEquals(20, circle.getDiameter(), 0);
}

@Test
public void test_getCircumference() {

    CircleClass circleClass = new CircleClass();
    Circle circle = circleClass.new Circle(10);

    assertEquals(62.8318, circle.getCircumference(), 0);
}