sdut-oop-6 计算各种图形的周长(多态)
定义接口或类 Shape,定义求周长的方法length()。
定义如下类,实现接口Shape或父类Shape的方法。
(1)三角形类Triangle (2)长方形类Rectangle (3)圆形类Circle等。
定义测试类ShapeTest,用Shape接口(或类)定义变量shape,用其指向不同类形的对象,输出各种图形的周长。并为其他的Shape接口实现类提供良好的扩展性。
提示: 计算圆周长时PI取3.14。
输入格式:
输入多组数值型数据(double);
一行中若有1个数,表示圆的半径;
一行中若有2个数(中间用空格间隔),表示长方形的长度、宽度。
一行中若有3个数(中间用空格间隔),表示三角形的三边的长度。(需要判断三个边长是否能构成三角形)
若输入数据中有0或负数,则不表示任何图形,周长为0。
输出格式:
行数与输入相对应,数值为根据每行输入数据求得的图形的周长。
输入样例:
在这里给出一组输入。例如:
1
2 3
4 5 6
2
-2
-2 -3
结尾无空行
输出样例:
在这里给出相应的输出。例如:
6.28
10.00
15.00
12.56
0.00
0.00
结尾无空行
代码实现
import java.util.Scanner;
class Circle implements Shape{
double dmyr;
Circle(){
dmyr = 0;
}
Circle(double dmyr){
this.dmyr = dmyr;
if(dmyr <= 0) this.dmyr = 0;
}
public double length() {
return 2 * 3.14 * dmyr;
}
}
class Rectangle implements Shape{
double da, db;
Rectangle(){
this.da = this.db = 0;
}
Rectangle(double da){
this.da = this.db = 0;
}
Rectangle(double da, double db){
this.da = da;
this.db = db;
if(da <= 0 || db <= 0){
this.da = this.db = 0;
}
}
public double length() {
return 2 * (da + db);
}
}
class Triangle implements Shape{
double da;
double db;
double dc;
Triangle(){
this.da = this.db = this.dc = 0;
}
Triangle(double da){
this.da = this.db = this.dc = 0;
}
Triangle(double da, double db){
this.da = this.db = this.dc = 0;
}
Triangle(double da, double db, double dc){
this.da = da;
this.db = db;
this.dc = dc;
if(da <= 0 || db <= 0 || dc <= 0 || !(da + db > dc && da + dc > db && db + dc > da)){
this.da = this.db = this.dc = 0;
}
}
public double length() {
return da + db + dc;
}
}
interface Shape{
double length();
}
public class Main {
public static void main(String[] args) {
Scanner dmy = new Scanner(System.in);
while(dmy.hasNextInt()) {
double[] l = new double[5];
String s;
s = dmy.nextLine();
String[] str = s.split(" ");
int cnt = 0;
for (String value : str) {
l[cnt++] = Double.parseDouble(value);
}
if(cnt == 1){
Circle C = new Circle(l[0]);
System.out.printf("%.2f\n", C.length());
}
else if (cnt == 2){
Rectangle r = new Rectangle(l[0], l[1]);
System.out.printf("%.2f\n", r.length());
}
else{
Triangle t = new Triangle(l[0], l[1], l[2]);
System.out.printf("%.2f\n", t.length());
}
}
}
}