Write an object oriented programming (JAVA) code.
Create a class called Circle. The class has an attribute radius, which default to 1 by the first no-arg constructor. The class also has another constructor that instantiates the radius to a given value. Provide methods that calculate the circumference and the area of the circle (use Math.PI and Math.pow). Provide set and get methods. The set method should verify that radius is greater than or equal to 0.0 and less than 20.0, otherwise it sets radius to 1. Write an application to test class Circle.
import java.util.Scanner; public class Circle { private double radius; public Circle() { this.radius = 1; } public Circle(double radius) { this.radius = radius; } public double getRadius() { return radius; } public void setRadius(double radius) { if(radius>=0.0 && radius<=20) this.radius = radius; else this.radius = 1; } public double calcCircumference () { return 2*Math.PI*radius; } public double calcArea(){ return radius*radius*Math.PI; } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Circle circle = new Circle(); System.out.print("Enter radius: "); double radius = scanner.nextDouble(); circle.setRadius(radius); System.out.println("Area = "+circle.calcArea()); System.out.println("Circumference = "+circle.calcCircumference()); } }
Get Answers For Free
Most questions answered within 1 hours.