請你實現一個基礎圖形類Graph,然後實現三角形類Triangle和矩形類Rectangle,繼承自Graph。根據輸入的邊數實現不同的對象,並計算面積。
輸入格式:
一行,一個整數n,表示圖形個數。
n行,每行是用空格隔開的整數。
輸出格式:
n行,每行是一個圖形的面積。
輸入樣例:
2
5 5
6 6 6
輸出樣例:
25
15
package javatest007; import java.util.Scanner; /* * 我們有一些圖形的邊長數據,這些圖形包括三角新和矩形,請你編寫一個程序求出它們的面積。 請你實現一個基礎圖形類Graph,然後實現三角形類Triangle和矩形類Rectangle,繼承自Graph。根據輸入的邊數實現不同的對象,並計算面積。 輸入格式: 一行,一個整數n,表示圖形個數。 n行,每行是用空格隔開的整數。 輸出格式: n行,每行是一個圖形的面積。 輸入樣例: 2 5 5 6 6 6 輸出樣例: 25 15 */ public class javatest008 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("請輸入圖形個數:"); Scanner in=new Scanner(System.in); int number=in.nextInt(); String[] str=new String[number]; for(int n=0;n<number;n++) { in.nextLine(); str[n]=in.nextLine(); //System.out.println(str[n]); } for(int i=0;i<number;i++) { String[] temp=str[i].split(" "); if(temp.length==2) { double c=Double.parseDouble(temp[0]); double d=Double.parseDouble(temp[1]); if(c<0||d<0) { System.out.println("無法構成矩形!"); }else { Rectangle rectangle=new Rectangle(c,d); System.out.println(rectangle.getArea()); } } if(temp.length==3) { double a=Double.parseDouble(temp[0]); double b=Double.parseDouble(temp[1]); double c=Double.parseDouble(temp[2]); if(a<0||b<0||c<0) { System.out.println("無法構成三角形!"); }else if(a+b>c&&b+c>a&&a+c>b) { Triangle triangle=new Triangle(a,b,c); triangle.getArea(); }else { System.out.println("無法構成三角形!"); } } } } }
graph類:
package javatest007;
public class Graph {
private String Identity="Graph";
double[] edge;//邊
public double[] getEdge()
{
return this.edge;
}
public String getIdentity()
{
return this.Identity;
}
}
rectangle類:
package javatest007;
public class Rectangle extends Graph {
private String Identity="Rectangle";
Rectangle()
{
this.edge[0]=0;
this.edge[1]=0;
}
Rectangle(double length,double width)
{
this.edge=new double[2];
this.edge[0]=length;
this.edge[1]=width;
}
public double getLength()
{
return this.edge[0];
}
public double getWidth()
{
return this.edge[1];
}
public String getIdentity()
{
return this.Identity;
}
public double getArea()
{
return this.edge[0]*this.edge[1];
}
}
triangle類:
package javatest007;
public class Triangle extends Graph {
private String Identity="Triangle";
Triangle()
{
this.edge[0]=0;
this.edge[1]=0;
this.edge[2]=0;
}
Triangle(double edgeA,double edgeB,double edgeC)
{
this.edge=new double[3];
this.edge[0]=edgeA;
this.edge[1]=edgeB;
this.edge[2]=edgeC;
}
public double getEdgeA()
{
return this.edge[0];
}
public double getEdgeB()
{
return this.edge[1];
}
public double getEdgeC()
{
return this.edge[2];
}
public String getIdentity()
{
return this.Identity;
}
public double getArea()
{
double p=0.5*(this.edge[0]+this.edge[1]+this.edge[2]);
return Math.sqrt(p*(p-this.edge[0])*(p-this.edge[1])*(p-this.edge[2]));
}
}