7-2 sdut-oop-6 計算各種圖形的周長(多態) (10 分)<接口|繼承|多態|分割字符串>


題目

點擊查看題目

定義接口或類 Shape,定義求周長的方法length()。

定義如下類,實現接口Shape或父類Shape的方法。

(1)三角形類Triangle (2)長方形類Rectangle (3)圓形類Circle等。

定義測試類ShapeTest,用Shape接口(或類)定義變量shape,用其指向不同類形的對象,輸出各種圖形的周長。並為其他的Shape接口實現類提供良好的擴展性。

提示: 計算圓周長時PI取3.14。

輸入格式:
輸入多組數值型數據(double);

一行中若有1個數,表示圓的半徑;

一行中若有2個數(中間用空格間隔),表示長方形的長度、寬度。

一行中若有3個數(中間用空格間隔),表示三角形的三邊的長度。(需要判斷三個邊長是否能構成三角形)

若輸入數據中有0或負數,則不表示任何圖形,周長為0。

輸出格式:
行數與輸入相對應,數值為根據每行輸入數據求得的圖形的周長。
輸入樣例:
在這里給出一組輸入。例如:

1
2 3
4 5 6
2
-2
-2 -3
結尾無空行
輸出樣例:
在這里給出相應的輸出。例如:
6.28
10.00
15.00
12.56
0.00
0.00
結尾無空行

# 代碼

import java.util.Scanner;

interface Shape{
	 double length();
}

class Triangle implements Shape{
	double a;
	double b;
	double c;
	public Triangle(double a,double b,double c) {
		this.a=a;
		this.b=b;
		this.c=c;
	    if(a+b<=c||a+c<=b||b+c<=a||a<=0||b<=0||c<=0) {
	    	this.a=0;
			this.b=0;
			this.c=0;
		}
	}
	public double length() {
		double ans=a+b+c;
		ans=(double)(Math.round(ans*100))/100;
		return ans;
	}
}

class Circle implements Shape{
	double r;
	public Circle(double r) {
		if(r<0) r=0;
		else
		this.r=r;
	}
	@Override
	public double length() {
		double ans=2*r*3.14;
		ans=(double)(Math.round(ans*100))/100;
		return ans;
	}
}
class Rectangle implements Shape{
     double a;
     double b;
    public Rectangle(double a,double b){
    	if(a<=0||b<=0) {
    		a=0;
    		b=0;
    	}
    	else {
    		this.a=a;
        	this.b=b;
    	}
    }
	@Override
	public double length() {
		double ans=(a+b)*2;
		ans=(double)(Math.round(ans*100))/100;
		return ans;
	}
}


public class Main
{
	 public static void main(String args[]) {
		Scanner sc=new Scanner(System.in);
		while(sc.hasNext()) {
			 Shape s;
			 int flag=1;
			String str=sc.nextLine();

			String[] a=str.split(" ");
			if(flag==0) {
				continue;
			}
			if(a.length==1) {
				double r=Double.parseDouble(a[0]);
				s=new Circle(r);
				System.out.printf("%.2f\n",s.length());
			}
			if(a.length==2) {
				double aa=Double.parseDouble(a[0]);
				double bb=Double.parseDouble(a[1]);
				s=new Rectangle(aa,bb);
				System.out.printf("%.2f\n",s.length());
			}
			if(a.length==3) {
				double aa=Double.parseDouble(a[0]);
				double bb=Double.parseDouble(a[1]);
				double cc=Double.parseDouble(a[2]);
			    s=new Triangle(aa,bb,cc);
			    System.out.printf("%.2f\n",s.length());
			}

		}
	       sc.close();
	 }
}     


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM