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

通过定义接口Shape及其实现类Triangle、Rectangle、Circle,使用多态特性实现不同图形周长的计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

Time Limit: 1000MS  Memory Limit: 65536KB
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。
Author

zhouxq

import java.util.*;

public class Main {
	public static void main(String[] args){
		Scanner in = new Scanner(System.in);
		while(true){
			String s = in.nextLine();
			String[] a = s.split(" ");
			Shape shape = null;
			switch(a.length){
			case 1:
				shape = new Circle(Double.parseDouble(a[0]));
				break;
			case 2:
				shape = new Rectangle(Double.parseDouble(a[0]), Double.parseDouble(a[1]));
				break;
			case 3:
				shape = new Triangle(Double.parseDouble(a[0]), Double.parseDouble(a[1]), Double.parseDouble(a[2]));
				break;
			}
			System.out.printf("%.2f\n", shape.length());
		}	
	}
}

interface Shape{
	double length();
}

class Circle implements Shape{
	public double length() {
		return Circle.PI * 2.0 * r;
	}
	private double r;
	static final double PI = 3.14;
	public Circle(double r){
		if(r <= 0)
			this.r = 0;
		else
			this.r = r;
	}
}

class Rectangle implements Shape{
	private double l, h;
	public Rectangle(double l, double h){
		if(l <= 0 || h <= 0){
			this.l = 0;
			this.h = 0;
		}
		else{
			this.l = l;
			this.h = h;
		}
	}
	public double length(){
		return (l+h) * 2.0;
	}
}

class Triangle implements Shape{
	private double a, b, c;
	public boolean True(double ...c){
		Arrays.sort(c);
		//System.out.println(c[0] +" " + c[1] + " " + c[2]);
		if(c[0]+c[1] > c[2])
			return true;
		else
			return false;
	}
	public Triangle(double a, double b, double c){
		if(a <= 0 || b <= 0 || c <= 0 || True(a, b, c) == false){
			this.a = 0;
			this.b = 0;
			this.c = 0;
		}
		else{
			this.a = a;
			this.b = b;
			this.c = c;
		}
	}
	public double length(){
		return a + b + c;
	}
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西杭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值