From a8065d7e1d4876b571354ec03e94a53343647e8c Mon Sep 17 00:00:00 2001 From: Sudipto Mallick Date: Tue, 2 Jan 2024 15:48:49 +0530 Subject: Wrote code for Java assignment #13 Demonstrating method overloading --- java/code/ShapeAreaCalculations.java | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 java/code/ShapeAreaCalculations.java diff --git a/java/code/ShapeAreaCalculations.java b/java/code/ShapeAreaCalculations.java new file mode 100644 index 0000000..0d00bff --- /dev/null +++ b/java/code/ShapeAreaCalculations.java @@ -0,0 +1,59 @@ +import java.util.Scanner; + +class Shape { + // Calculates the area of a triangle. + static double area(double a, double b, double c) { + double s = (a + b + c) / 2.0; + return Math.sqrt(s * (s - a) * (s - b) * (s - c)); + } + // Area of a rectangle. + static int area(int length, int width) { + return length * width; + } + // Area of a square. + static int area(int sideLength) { + return sideLength * sideLength; + } + // Area of a circle. + static double area(double radius) { + return Math.PI * radius * radius; + } +} + +class AreaCalc { + public static void main(String args[]) { + var sc = new Scanner(System.in); + System.out.println("Choose the shape: "); + System.out.println("1. Triangle\n2. Rectangle\n3. Square\n4.Circle"); + System.out.print("Enter your choice: "); + var choice = sc.nextInt(); + switch (choice) { + case 1: + System.out.print("Enter sides: "); + var a = sc.nextDouble(); + var b = sc.nextDouble(); + var c = sc.nextDouble(); + System.out.println("Area of a triangle: " + Shape.area(a, b, c)); + break; + case 2: + System.out.print("Enter length and width: "); + var len = sc.nextInt(); + var wid = sc.nextInt(); + System.out.println("Area of a rectangle: " + Shape.area(len, wid)); + break; + case 3: + System.out.print("Enter side length: "); + var sidelen = sc.nextInt(); + System.out.println("Area of a square: " + Shape.area(sidelen)); + break; + case 4: + System.out.print("Enter radius: "); + var r = sc.nextDouble(); + System.out.println("Area of a square: " + Shape.area(r)); + break; + default: + System.out.println("Invalid choice"); + break; + } + } +} -- cgit 1.4.1-2-gfad0