Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public abstract class Shape {
- protected double area;
- public double getArea() {
- return area;
- }
- protected abstract void onAreaChange();
- }
- public class Triangle extends Shape {
- protected double base;
- protected double height;
- public Triangle setBase(double base) {
- this.base = base;
- onAreaChange();
- return this;
- }
- public Triangle setHeight(double height) {
- this.height = height;
- onAreaChange();
- return this;
- }
- @Override
- public void onAreaChange() {
- this.area = 0.5 * this.base * this.height;
- }
- }
- public class Rectangle extends Shape {
- protected double height;
- protected double width;
- public Rectangle setHeight(double height) {
- this.height = height;
- onAreaChange();
- return this;
- }
- public Rectangle setWidth(double width) {
- this.width = width;
- onAreaChange();
- return this;
- }
- @Override
- public void onAreaChange() {
- this.area = this.height * this.width;
- }
- }
- public class Circle extends Shape {
- protected double radius;
- protected final double PI = 3.14159265;
- public Circle setRadius(double radius) {
- this.radius = radius;
- onAreaChange();
- return this;
- }
- @Override
- public void onAreaChange() {
- this.area = this.radius * this.radius * PI;
- }
- }
- import java.util.Scanner;
- public class Main {
- public static Scanner scan = new Scanner(System.in);
- public static void main(String[] args) {
- while (true) {
- System.out.println("Enter the number which you want to compute the area");
- System.out.print("(1) Triangle (2) Rectangle (3) Circle ? ");
- switch (scan.nextInt()) {
- case 1:
- Triangle triangle = new Triangle();
- System.out.print("Base: ");
- triangle.setBase(scan.nextDouble());
- System.out.print("Height: ");
- triangle.setHeight(scan.nextDouble());
- System.out.println("Area of triangle: " + triangle.getArea());
- break;
- case 2:
- Rectangle rectangle = new Rectangle();
- System.out.print("Width: ");
- rectangle.setWidth(scan.nextDouble());
- System.out.print("Height: ");
- rectangle.setHeight(scan.nextDouble());
- System.out.println("Area of rectangle: " + rectangle.getArea());
- break;
- case 3:
- Circle circle = new Circle();
- System.out.print("Radius: ");
- circle.setRadius(scan.nextDouble());
- System.out.println("Area of circle: " + circle.getArea());
- break;
- default:
- System.out.println("What do u mean?");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement