From 77a06188a4cec38407578d2a4f78e22de308583a Mon Sep 17 00:00:00 2001 From: Sudipto Mallick Date: Mon, 8 Jan 2024 14:21:06 +0530 Subject: Implement Java Assignment #14 --- java/code/AbstractShapeCalculations.java | 82 ++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 java/code/AbstractShapeCalculations.java (limited to 'java/code') diff --git a/java/code/AbstractShapeCalculations.java b/java/code/AbstractShapeCalculations.java new file mode 100644 index 0000000..3f18c0c --- /dev/null +++ b/java/code/AbstractShapeCalculations.java @@ -0,0 +1,82 @@ +import java.util.Scanner; +import java.util.InputMismatchException; + +abstract class Shape { + abstract double area(); + abstract void display(); +} + +class Rectangle extends Shape { + double length, width; + Rectangle(double len, double wid) { + length = len; + width = wid; + } + double area() { + return length * width; + } + void display() { + System.out.println("A rectangle with length " + length + " units and width " + width + " units has the area of " + area() + " square units."); + } +} + +class Circle extends Shape { + double radius; + Circle(double r) { + radius = r; + } + double area() { + return Math.PI * radius * radius; + } + void display() { + System.out.println("A circle with radius " + radius + " units has the area of " + area() + " square units."); + } +} + +class Triangle extends Shape { + double a, b, c; + Triangle(double s1, double s2, double s3) { + a = s1; + b = s2; + c = s3; + } + double perimeter() { + return a + b + c; + } + double area() { + var s = perimeter() / 2.0; + return Math.sqrt(s * (s - a) * (s - b) * (s - c)); + } + void display() { + System.out.println("A triangle with side lengths " + a + " units, " + b + "units and " + c + " units has the area of " + area() + " square units."); + } +} + +class AbstractShapeCalculations { + public static void main(String[] args) { + try { + Scanner sc = new Scanner(System.in); + System.out.println("Calculate and display shapes\n"); + System.out.println("Rectangle"); + System.out.print(" Enter length: "); + double length = sc.nextDouble(); + System.out.print(" Enter width: "); + double width = sc.nextDouble(); + Shape s; + s = new Rectangle(length, width); + s.display(); + System.out.println("Circle"); + System.out.print(" Enter radius: "); + double radius = sc.nextDouble(); + s = new Circle(radius); + s.display(); + System.out.println("Triangle"); + System.out.print(" Enter three side lengths: "); + double a = sc.nextDouble(), b = sc.nextDouble(), c = sc.nextDouble(); + s = new Triangle(a, b, c); + s.display(); + } catch (InputMismatchException e) { + System.err.println("Invalid numbers in input"); + } + } +} -- cgit 1.4.1-2-gfad0