7-2 sdut-oop-6 计算各种图形的周长(多态) (10 分)

 
import java.util.*;
 
public class Main
{
	public static void main(String[] args)
	{
		Scanner cin = new Scanner(System.in);
		double a,b,c;
		Shape x;
		String str;
		String []s;
		while(cin.hasNextLine())//cin.nextLine()吸收空格和tab,遇到回车停止。
		{
			str = cin.nextLine();
			s = str.split(" ");
			if(s.length==1)//判断输入的数字有几个,若只要一个即为圆形,两个即为长方形,三个即为三角形
			{
				a = Double.parseDouble(s[0]);
				x = new Circle(a);
				System.out.printf("%.2f\n",x.length());
			}
			else if(s.length==2)
			{
				a = Double.parseDouble(s[0]);
				b = Double.parseDouble(s[1]);
				x = new Rectangle(a,b);
				System.out.printf("%.2f\n",x.length());
			}
			else if(s.length==3)
			{
				a = Double.parseDouble(s[0]);
				b = Double.parseDouble(s[1]);
				c = Double.parseDouble(s[2]);
				x = new Triangle(a,b,c);
				System.out.printf("%.2f\n",x.length());
			}
		}
		cin.close();
	}
}
 
interface Shape//接口,实现输入各图形的周长
{
	public double length();
}
 
class Triangle implements Shape//三角形类
{
	double a,b,c;
	Triangle(double a,double b,double c)//构造方法
	{
		this.a = a;
		this.b = b;
		this.c = c;
	}
	public double length()//重写实现周长的方法
	{
		if(a<=0||b<=0||c<=0)//输入是否非法
			return 0;
		if(a+b<=c||a+c<=b||b+c<=a)//是否能构成三角形
			return 0;
		return a + b + c;
	}
}
 
class Rectangle implements Shape//长方形类
{
	double a,b;
	Rectangle(double a,double b)//构造方法
	{
		this.a = a;
		this.b = b;
	}
	public double length()//重写实现周长方法
	{
		if(a<=0||b<=0)//输入是否非法
			return 0;
		return (a + b) * 2;
	}
}
 
class Circle implements Shape//圆形类
{
	double a;
	Circle(double a)//构造方法
	{
		this.a = a;
	}
	public double length()//重写实现周长方法
	{
		if(a<=0)//输入是否非法
			return 0;
		return a * 3.14 * 2;
	}
}

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值