定义三角形类Criangle,其中有成员x,y,z,作为三条边的长。
构造方法Criangle(a,b,c)分别给x,y,z赋值;
方法求面积getArea;
方法显示三角形边长信息showInfo。
在主类方法中构造一个Criangle对象(三边为命令输入的三个数),
当三条边不能构成一个三角形时要抛出自定义异常NoCriangleException,
异常类能捕获异常并处理,否则显示三角形面积Area和边长Info。
public class Criangle {
private int x;
private int y;
private int z;
public Criangle(int x, int y, int z) {
super();
this.x = x;
this.y = y;
this.z = z;
}
public double getArea() throws NoCriangleException {
if (!isCriangle()) {
throw new NoCriangleException("不是三角形");
}
double p = (this.x + this.y + this.z) / 2;
return Math.sqrt(p * (p - this.x) * (p - this.y) * (p - this.z));
}
public boolean isCriangle() {
if ((this.x + this.y > this.z) && (this.x + this.z > this.y)
&& (this.y + this.z > this.x)) {
return true;
}
return false;
}
public void showInfo() {
System.out.println("边长x="+this.x);
System.out.println("边长y="+this.y);
System.out.println("边长z="+this.z);
}
}