问题描述:
自定义类Sanj,其中有成员 x,y,z,作为三边长,构造方法Sanj(a,b,c)分别给x,y,z赋值,方法求面积getArea和显示三角形信息(三个边长)showInfo。要求:当输入a,b,c不能够组成一个三角形时,要抛出一个运行异常,捕捉到该异常后,显示系数输入有错误,并终止程序。
源代码(可运行):
import java.util.Scanner;
public class SanjiaoxingArea {
public static void main(String[] args) {
// TODO Auto-generated method stub
double d;
double e;
double f;
System.out.println("请输入三角形的三条边长:");
Scanner input=new Scanner(System.in);
d=input.nextDouble();
e=input.nextDouble();
f=input.nextDouble();
Sanj q=new Sanj(d,e,f);
q.showInfo();
q.getArea();
}
}
class Sanj
{
double x;
double y;
double z;
public Sanj() {}
public Sanj(double a,double b,double c)
{
x=a;
y=b;
z=c;
}
public void getArea()
{
double s;
double p;
if(x+y<=z)
{
System.out.println("NotSanjiaoException");
}
else if(x+z<=y)
{
System.out.println("NotSanjiaoException");
}
else if(y+z<=x)
{
System.out.println("NotSanjiaoException");
}
else
{p=(x+y+z)*0.5;
s=Math.sqrt(p*(p-x)*(p-y)*(p-z));
System.out.println("三角形的面积为:"+s);
}
}
public void showInfo()
{
if(x+y<=z)
{
System.out.println("NotSanjiaoException");
}
else if(x+z<=y)
{
System.out.println("NotSanjiaoException");
}
else if(y+z<=x)
{
System.out.println("NotSanjiaoException");
}
else
{
System.out.println("“三角形的三条边为:"+x+" "+y+" "+z);
}
}
}