1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
|
import java.util.Scanner;
interface Shape { double getArea(); double getPerimeter(); }
interface Factory { Shape create(double ... param); }
enum Type { RECTANGLE, TRIANGLE }
class Rectangle implements Shape {
private double w, h;
public Rectangle(double w, double h) { this.w = w; this.h = h; }
@Override public String toString() { return "w=" + w + ",h=" + h + ",perimeter=" + getPerimeter() + ",area=" + String.format("%.2f", getArea()); }
@Override public double getPerimeter() { return 2 * (w + h); }
@Override public double getArea() { return w * h; } }
class Triangle implements Shape {
private double a, b, c;
public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; }
@Override public String toString() { return "a=" + a + ",b=" + b + ",c=" + c + ",perimeter=" + getPerimeter() + ",area=" + String.format("%.2f", getArea()); }
@Override public double getPerimeter() { return a + b + c; }
@Override public double getArea() { double p = (a + b + c) / 2.0; return Math.sqrt(p * (p - a) * (p - b) * (p - c)); } }
class RectangleFactory implements Factory {
@Override public Rectangle create(double ... param) { return param.length == 2 ? new Rectangle(param[0], param[1]) : null; } }
class TriangleFactory implements Factory {
@Override public Triangle create(double ... param) { return param.length == 3 ? new Triangle(param[0], param[1], param[2]) : null; } }
public class Test {
public static void main(String[] args) { Scanner sin = new Scanner(System.in); Rectangle r = null; Triangle a = null; for (int i = 0; i < 2; ++i) { String type = sin.next(); if (type.equals(Type.RECTANGLE.name())) { r = new RectangleFactory().create(sin.nextDouble(), sin.nextDouble()); } if (type.equals(Type.TRIANGLE.name())) { a = new TriangleFactory().create(sin.nextDouble(), sin.nextDouble(), sin.nextDouble()); } } sin.close(); System.out.println(r); System.out.println(a); } }
|