7-2 sdut-oop-6 计算各种图形的周长(多态) (10 分)<接口|继承|多态|分割字符串>
题目
点击查看题目
定义接口或类 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; interface Shape{ double length(); } class Triangle implements Shape{ double a; double b; double c; public Triangle(double a,double b,double c) { this.a=a; this.b=b; this.c=c; if(a+b<=c||a+c<=b||b+c<=a||a<=0||b<=0||c<=0) { this.a=0; this.b=0; this.c=0; } } public double length() { double ans=a+b+c; ans=(double)(Math.round(ans*100))/100; return ans; } } class Circle implements Shape{ double r; public Circle(double r) { if(r<0) r=0; else this.r=r; } @Override public double length() { double ans=2*r*3.14; ans=(double)(Math.round(ans*100))/100; return ans; } } class Rectangle implements Shape{ double a; double b; public Rectangle(double a,double b){ if(a<=0||b<=0) { a=0; b=0; } else { this.a=a; this.b=b; } } @Override public double length() { double ans=(a+b)*2; ans=(double)(Math.round(ans*100))/100; return ans; } } public class Main { public static void main(String args[]) { Scanner sc=new Scanner(System.in); while(sc.hasNext()) { Shape s; int flag=1; String str=sc.nextLine(); String[] a=str.split(" "); if(flag==0) { continue; } if(a.length==1) { double r=Double.parseDouble(a[0]); s=new Circle(r); System.out.printf("%.2f\n",s.length()); } if(a.length==2) { double aa=Double.parseDouble(a[0]); double bb=Double.parseDouble(a[1]); s=new Rectangle(aa,bb); System.out.printf("%.2f\n",s.length()); } if(a.length==3) { double aa=Double.parseDouble(a[0]); double bb=Double.parseDouble(a[1]); double cc=Double.parseDouble(a[2]); s=new Triangle(aa,bb,cc); System.out.printf("%.2f\n",s.length()); } } sc.close(); } }
本文作者:kingwzun
本文链接:https://www.cnblogs.com/kingwz/p/15543468.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步