Answer to Question #313302 in Java | JSP | JSF for neha

Question #313302

create class calculation with an abstract method area().Create Rectangle and Triangle subclasses of calculation and find area of rectangle and triangle.


1
Expert's answer
2022-03-17T13:55:48-0400


import java.util.Scanner;


abstract class Shape {
	public abstract double area();
}


class Rectangle extends Shape {
	private double w;
	private double h;


	public Rectangle() {
	}


	public Rectangle(double w, double h) {
		this.w = w;
		this.h = h;
	}


	@Override
	public double area() {
		return w * h;
	}


}


class RightAngledTriangle extends Shape {
	private double w;
	private double h;


	public RightAngledTriangle() {
	}


	public RightAngledTriangle(double w, double h) {
		this.w = w;
		this.h = h;
	}


	@Override
	public double area() {
		return 0.5 * w * h;
	}


}


public class App {


	/** Main Method */
	public static void main(String[] args) {
		Scanner keyBoard = new Scanner(System.in); // Create a Scanner
		int ch = -1;
		Shape shape;
		while (ch != 3) {
			System.out.println("1. Computes the area & perimeter a rectangle");
			System.out.println("2. Computes the area & perimeter a right-angled triangle");
			System.out.println("3. Exit");
			System.out.print("Your choice: ");
			ch = keyBoard.nextInt();
			switch (ch) {
			case 1:
				System.out.print("Enter the width of a rectangle: ");
				double w = keyBoard.nextDouble();
				System.out.print("Enter the height of a rectangle: ");
				double h = keyBoard.nextDouble();
				shape = new Rectangle(w, h);
				System.out.println("The area of a rectangle: " + shape.area());
				break;
			case 2:
				System.out.print("Enter the width of a right-angled triangle: ");
				w = keyBoard.nextDouble();
				System.out.print("Enter the height of a right-angled triangle: ");
				h = keyBoard.nextDouble();
				shape = new RightAngledTriangle(w, h);
				System.out.println("The area of a right-angled triangle: " + shape.area());
				break;
			case 3:
				break;
			default:
				break;
			}
		}
		keyBoard.close();
	}


}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS