Java练习 SDUT-3338_计算各种图形的周长(接口与多态)

计算各种图形的周长(接口与多态)

Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem 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

Sample Output

6.28
10.00
15.00
12.56
0.00
0.00

Hint

构造三角形时要判断给定的三边的长度是否能组成一个三角形,即符合两边之和大于第三边的规则;
计算圆周长时PI取3.14。

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())
		{
			str = cin.nextLine();
			s = str.split(" ");
			if(s.length==1)
			{
				a = Double.parseDouble(s[0]);
				x = new Circle(a);
				System.out.printf("%.2f
",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
",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
",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;
	}
}
原文地址:https://www.cnblogs.com/luoxiaoyi/p/9934597.html