Java-計算各種圖形的周長(介面與多型)
阿新 • • 發佈:2019-01-30
計算各種圖形的周長(介面與多型)
Time Limit: 1000 ms Memory Limit: 65536 KiBProblem Description
定義介面Shape,定義求周長的方法length()。定義如下類實現介面Shape的抽象方法:(1)三角形類Triangle (2)長方形類Rectangle (3)圓形類Circle等。定義測試類ShapeTest,用Shape介面定義變數shape,用其指向不同類形的物件,輸出各種圖形的周長。併為其他的Shape介面實現類提供良好的擴充套件性。Input
輸入多組數值型資料(double);一行中若有1個數,表示圓的半徑;一行中若有2個數(中間用空格間隔),表示長方形的長度、寬度。一行中若有3個數(中間用空格間隔),表示三角形的三邊的長度。若輸入資料中有負數,則不表示任何圖形,周長為0。Output
Sample Input
1 2 3 4 5 6 2 -2 -2 -3
Sample Output
6.28 10.00 15.00 12.56 0.00 0.00
Hint
構造三角形時要判斷給定的三邊的長度是否能組成一個三角形,即符合兩邊之和大於第三邊的規則;計算圓周長時PI取3.14。Source
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); ShapeTest shapetest = new ShapeTest(); while(sc.hasNext()) { Shape shape = null; String str = sc.nextLine(); String [] array = str.split(" "); if(array.length == 1) { double r = Double.parseDouble(array[0]); shape = new Circle(r); } else if(array.length == 2) { double l = Double.parseDouble(array[0]); double w = Double.parseDouble(array[1]); shape = new Rectangle(l, w); } else if(array.length == 3) { double a = Double.parseDouble(array[0]); double b = Double.parseDouble(array[1]); double c = Double.parseDouble(array[2]); shape = new Triangle(a, b, c); } if(shape != null) { double area = shapetest.length(shape); System.out.printf("%.2f\n", area); } else { System.out.println("0.00"); } } sc.close(); } } interface Shape { //定義介面 public double length(); } // 介面重寫
class Triangle implements Shape {
double a, b, c;
public Triangle(double a, double b, double c) {
super();
if(a < 0 || b < 0 || c < 0) {
a = 0; b = 0; c = 0;
}
if(a + b > c && a + c > b && b + c > a) {
this.a = a;
this.b = b;
this.c = c;
}
}
public double length() {
return a + b + c;
}
}
class Rectangle implements Shape {
double l, w;
public Rectangle(double l, double w) {
if(l < 0 || w < 0) {
l = 0; w = 0;
}
else {
this.l = l;
this.w = w;
}
}
public double length() {
return 2 * (this.w + this.l);
}
}
class Circle implements Shape{
double r;
public Circle(double r) {
if(r <= 0) {
r = 0;
}
this.r = r;
}
public double length() {
return 2 * 3.14 * this.r;
}
}
class ShapeTest { ////定義測試類ShapeTest,用Shape介面定義變數shape,用其指向不同類形的物件,輸出各種圖形的周長。
public double length(Shape shape) {
return shape.length();
}
}