From 6a352be9778f6220030f3b6c0163eba2374bb52b Mon Sep 17 00:00:00 2001 From: cdjole Date: Fri, 9 Nov 2018 01:07:59 +0100 Subject: [PATCH] Calculate circle area. (#5644) --- .../java/com/baeldung/area/circle/Circle.java | 30 ++++++++++++++++ .../com/baeldung/area/circle/CircleArea.java | 36 +++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 core-java/src/main/java/com/baeldung/area/circle/Circle.java create mode 100644 core-java/src/main/java/com/baeldung/area/circle/CircleArea.java diff --git a/core-java/src/main/java/com/baeldung/area/circle/Circle.java b/core-java/src/main/java/com/baeldung/area/circle/Circle.java new file mode 100644 index 0000000000..595bc3d2e7 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/area/circle/Circle.java @@ -0,0 +1,30 @@ +package com.baeldung.area.circle; + +public class Circle { + + private double radius; + + public Circle(double radius) { + this.radius = radius; + } + + public double getRadius() { + return radius; + } + + public void setRadius(double radius) { + this.radius = radius; + } + + public double getArea() { + return calculateArea(); + } + + private double calculateArea() { + return radius * radius * Math.PI; + } + + public String toString() { + return "The area of the circle [radius = " + radius + "]: " + calculateArea(); + } +} diff --git a/core-java/src/main/java/com/baeldung/area/circle/CircleArea.java b/core-java/src/main/java/com/baeldung/area/circle/CircleArea.java new file mode 100644 index 0000000000..4d78637af6 --- /dev/null +++ b/core-java/src/main/java/com/baeldung/area/circle/CircleArea.java @@ -0,0 +1,36 @@ +package com.baeldung.area.circle; + +import java.util.InputMismatchException; +import java.util.Scanner; + +public class CircleArea { + + public static void main(String[] args) { + if (args.length > 0) { + try { + double radius = Double.parseDouble(args[0]); + calculateArea(radius); + } catch (NumberFormatException nfe) { + System.out.println("Invalid value for radius"); + System.exit(0); + } + } + + try (Scanner scanner = new Scanner(System.in)) { + System.out.println("Please enter radius value: "); + double radius = scanner.nextDouble(); + calculateArea(radius); + } catch (InputMismatchException e) { + System.out.println("Invalid value for radius"); + System.exit(0); + } + + Circle circle = new Circle(7); + System.out.println(circle); + } + + private static void calculateArea(double radius) { + double area = radius * radius * Math.PI; + System.out.println("The area of the circle [radius = " + radius + "]: " + area); + } +}