In: Computer Science
Instructions
Write a Circle class (Circle.java) that has the following fields:
- radius (double)
- PI (final double initialized to 3.1415) // no need to have setters or getters for this
Include the following methods:
- Constructor (accepts radius of circle as an argument)
- Constructor (no argument that sets radius to 0.0)
- setRadius (set method for radius field)
- getRadius (get method for radius field)
- calcArea (calculates and returns area of circle: area = PI * radius * radius)
- calcDiameter (calculates and returns diameter of circle: diameter = radius * 2)
- calcCircumference (calculates and returns circumference of circle: circumference = 2* PI * radius)
Write a test program (TestCircle.java) that will ask user for the radius, creates the circle object, and then displays the area, diameter, and circumference.
Make sure to create 2 circle object instances - one with the radius as an argument, one without but sets the radius with the setRadius() method.
Thank you so much for your help!!
// Screenshot of the code & output
// Code to copy
Circle.java
public class Circle {
private double radius;
final double PI = 3.1415;
// default-constructor
public Circle ()
{
this.radius=0.0;
}
//argument-constructor
public Circle (double r)
{
this.radius=r;
}
public double getRadius()
{
return radius;
}
public void setRadius(double radius)
{
this.radius = radius;
}
// calcArea method to calculate Circle Area
public double calcArea() {
double area = PI * radius *
radius;
return area;
}
// calcDiameter method to calculate Circle
Diameter
public double calcDiameter() {
double diameter = radius * 2;
return diameter;
}
// calcCircumference method to calculate Circle
Circumference
public double calcCircumference() {
double circumference = 2* PI *
radius;
return circumference;
}
}
TestCircle.java
import java.util.Scanner;
import java.text.DecimalFormat;
public class TestCircle {
public static void main(String[] args) {
DecimalFormat df = new
DecimalFormat("0.00");
double radius;
Scanner input=new
Scanner(System.in);
System.out.print("Enter radius of circle :");
radius=input.nextDouble();
// circle object with out radius
Circle c1=new Circle ();
c1.setRadius(5);
System.out.println("\nCircle-1 object with out radius ");
System.out.println(df.format(c1.calcArea()));
System.out.println(df.format(c1.calcDiameter()));
System.out.println(df.format(c1.calcCircumference()));
// circle object with radius
Circle c2=new Circle
(radius);
System.out.println("\nCircle-2
object with radius ");
System.out.println(df.format(c2.calcArea()));
System.out.println(df.format(c2.calcDiameter()));
System.out.println(df.format(c2.calcCircumference()));
// closing scanner object
input.close();
}
}