计算各种图形的周长

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

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
 
 
 
 
 
 
import java.util.*;

interface Shape{	
public 	void length();
}
public class Main {
	
	public static void main(String[] args) {
		Scanner reader = new Scanner(System.in);
       while(reader.hasNext()){
         String str=reader.nextLine();
         String z[]=new String[3];
         double a[]=new double [3];
         z=str.split(" ");  
         int t=z.length;
          for(int i=0;i<z.length;i++){
        	  a[i]=Double.valueOf(z[i]);
              if(a[i]<=0){
            	  t=0;
              }
          }
          ShapeTest  tew=new ShapeTest(t,a);
          tew.test();
       }
	}
}
class ShapeTest{
	int t;
	double a[];
	public ShapeTest(int t,double a[]){
		this.a=a;
		this.t=t;
	}
	void  test(){
	  Shape shape;
	  if(t==0){
		  System.out.println("0.00");
	  }
	  else if(t==1){
      	 shape=new Circle(a);
      	  shape.length();
        }
        else if(t==2){
      	  shape =new Rectangle(a);
      	  shape.length();
        }
        else if (t==3){
      	  shape=new Triangle(a);
      	  shape.length();
        }
}
}
class Triangle implements Shape{
	
	double a[];
	Triangle (double a [])
	{
		this.a=a;
	}
	public void length() {
		if(a[0]+a[1]>a[2]&&a[0]+a[2]>a[1]&&a[2]+a[1]>a[0]){
		double v=a[0]+a[1]+a[2];
		System.out.println(String.format("%.2f", v));}
		else{
			System.out.println("0.00");
		}
	}
	
}
class Rectangle implements Shape{
	double a[];
	Rectangle(double a []){
		this.a=a;
	}
	public void length(){
		double z=a[0]*2+a[1]*2;
		System.out.println(String.format("%.2f", z));
	}
}
class Circle implements Shape{
	double a[];
	
	
	public Circle(double[] a) {
		// TODO Auto-generated method stub
        this.a=a;
	}
	public void length(){
		double v=a[0]*3.14*2;
		System.out.println(String.format("%.2f", v));
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值