生活随笔
收集整理的這篇文章主要介紹了
计算各种图形的周长(接口与多态)_JAVA
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Description
定義接口Shape,定義求周長的方法length()。
定義如下類實現接口Shape的抽象方法:
(1)三角形類Triangle (2)長方形類Rectangle (3)圓形類Circle等。
定義測試類ShapeTest,用Shape接口定義變量shape,用其指向不同類形的對象,輸出各種圖形的周長。并為其他的Shape接口實現類提供良好的擴展性。
Input
輸入多組數值型數據(double);
一行中若有1個數,表示圓的半徑;
一行中若有2個數(中間用空格間隔),表示長方形的長度、寬度。
一行中若有3個數(中間用空格間隔),表示三角形的三邊的長度。
若輸入數據中有負數,則不表示任何圖形,周長為0。
Output
行數與輸入相對應,數值為根據每行輸入數據求得的圖形的周長(保留2位小數)。
Sample
Input
1
2 3
4 5 6
2
-2
-2 -3
Output
6.28
10.00
15.00
12.56
0.00
0.00
Hint
構造三角形時要判斷給定的三邊的長度是否能組成一個三角形,即符合兩邊之和大于第三邊的規則;
計算圓周長時PI取3.14。
import java
.util
.*
;
interface Shape{public void length();
}
class Triangle implements Shape{double a
, b
, c
;public Triangle(double a
, double b
, double c
) {this.a
= a
;this.b
= b
;this.c
= c
;} public void length(){if(a
<= 0 || b
<= 0 || c
<= 0){System
.out
.print("0.00\n");}else if(a
+b
<=c
||a
+c
<=b
||c
+b
<=a
){System
.out
.print("0.00\n");}else{System
.out
.printf("%.2f\n", a
+b
+c
);}}
}
class Rectangle implements Shape{double a
, b
;public Rectangle(double a
, double b
) {this.a
= a
;this.b
= b
;}public void length(){if(a
<= 0 || b
<= 0){System
.out
.print("0.00\n");}else{System
.out
.printf("%.2f\n", 2*(a
+b
));}}
}
class Circle implements Shape{double a
;public Circle(double a
) {this.a
= a
;}public void length(){if(a
<= 0){System
.out
.print("0.00\n");}else{System
.out
.printf("%.2f\n", 2*3.14*a
);}}
}
public class Main {public static void main(String args
[]){Scanner reader
= new Scanner(System
.in
);while(reader
.hasNext()){String ch
= reader
.nextLine();String a
[] = ch
.split(" ");int c
[] = new int[5];int i
;for(i
= 0; i
< a
.length
; i
++) {c
[i
] = Integer
.parseInt(a
[i
]);}if(i
== 1) {Circle x
= new Circle(c
[0]);x
.length();}else if(i
== 2) {Rectangle x
= new Rectangle(c
[0], c
[1]);x
.length();}else {Triangle x
= new Triangle(c
[0], c
[1], c
[2]);x
.length();}}reader
.close();}}
總結
以上是生活随笔為你收集整理的计算各种图形的周长(接口与多态)_JAVA的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。