create class calculation with an abstract method area().Create Rectangle and Triangle subclasses of calculation and find area of rectangle and triangle.
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();
}
}
Comments
Leave a comment