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

Problem Description
定义接口Shape,定义求周长的方法length()。
定义如下类实现接口Shape的抽象方法:
(1)三角形类Triangle (2)长方形类Rectangle (3)圆形类Circle等。
定义测试类ShapeTest,用Shape接口定义变量shape,用其指向不同类形的对象,输出各种图形的周长。并为其他的Shape接口实现类提供良好的扩展性。
Input
输入多组数值型数据(double);
一行中若有1个数,表示圆的半径;
一行中若有2个数(中间用空格间隔),表示长方形的长度、宽度。
一行中若有3个数(中间用空格间隔),表示三角形的三边的长度。
 
若输入数据中有负数,则不表示任何图形,周长为0。
Output
行数与输入相对应,数值为根据每行输入数据求得的图形的周长(保留2位小数)。
Example Input
1
2 3
4 5 6
2
-2
-2 -3
Example Output
6.28
10.00
15.00
12.56
0.00
0.00
Hint
构造三角形时要判断给定的三边的长度是否能组成一个三角形,即符合两边之和大于第三边的规则;
计算圆周长时PI取3.14。

判断三角形的条件:任意两边之和大于第三边(之间用&&而不是||)



import java.util.Scanner;

public class Main {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		ShapeTest shapetest = new ShapeTest();
		while (sc.hasNext()) {
			Shape shape = null;
			String str = sc.nextLine();
			String[] array = str.split(" ");
			if (array.length == 1) {
				double r = Double.parseDouble(array[0]);
				shape=new Circle(r);
				
			} else if (array.length == 2) {
				double l = Double.parseDouble(array[0]);
				double w =Double.parseDouble(array[1]);
				shape=new Rectangle(l, w);
				
			} else if (array.length == 3) {
				double a = Double.parseDouble(array[0]);
				double b = Double.parseDouble(array[1]);
				double c = Double.parseDouble(array[2]);
				shape=new Triangle(a, b, c) ;
			}
			if(shape!=null){
				double area=shapetest.length(shape);
				System.out.printf("%.2f\n",area);
			}
			else{
				System.out.println("0.00");
			}
		}

		sc.close();
	}
}

interface Shape {
	public double length();
}

class Triangle implements Shape {
	double a, b, c;

	public Triangle(double a, double b, double c) {
		if (a < 0 || b < 0 || c < 0) {
			a = 0;
			b = 0;
			c = 0;
		}
		if (a + b > c && a + c > b && b + c > a) { //注意&&
			this.a = a;
			this.b = b;
			this.c = c;
		}
	}

	public double length() {
		return a + b + c;
	}

}

class Rectangle implements Shape {

	double l, w;

	public Rectangle(double l, double w) {
		if (l < 0 || w < 0) {
			l = 0;
			w = 0;
		}
		this.l = l;
		this.w = w;
	}

	public double length() {
		return 2 * (l + w);
	}

}

class Circle implements Shape {

	double r;

	public Circle(double r) {
		if (r < 0) {
			r = 0;
		}
		this.r = r;
	}

	public double length() {
		return 2 * 3.14 * r;
	}

}

class ShapeTest {
	public double length(Shape shape) {
		return shape.length();
	}
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值