1.功能描述:编写三角形的类,实现使用海伦公式求三角形的面积和三角形的周长,要求有三角形三条边是否能构成三角形的验证。给出实例代码和测试代码。
2.三角形示例代码:
package cn.wdl.test3;
public class Triangle {
//三角形的三条边:a,b,c
private double a=0;
private double b=0;
private double c=0;
//三角形的三条边能不能构成三角形,flag:true/false
private boolean flag=true;//如果有能构成三角形为true,否则为false
public double getA() {
return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
public boolean isFlag() {
return flag;
}
//构造方法,无参数的
public Triangle() {
a=3.0;
b=4.0;
c=5.0;
validate();
}
public Triangle(double a,double b,double c) {
this.a=a;
this.b=b;
this.c=c;
validate();
}
//验证三角形的三条边是不是合法
//1.任意二边之和大于第三边
//2.任意二边之差小于第三边
private void validate() {
//1.任意二边之和大于第三边
if((a+b)<=c || (a+c)<=b || (b+c)<=a) {
flag = false;
}
//2.任意二边之差小于第三边
if((a-c)>=b || (a-b)>=c || (b-c)>=a) {
flag = false;
}
}
//求三角形的周长
public double perimeter() {
return a+b+c;
}
//求三角的面积
public double area() {
double p=(a+b+c)/2;
return Math.sqrt(p*(p-a)*(p-b)*(p-c));
}
}
3.测试代码:
package cn.wdl.test3;
public class TestTriangle {
public static void main(String[] args) {
Triangle tri1 = new Triangle();
if(tri1.isFlag()) {
System.out.println("边长为:"+tri1.getA()+","+tri1.getB()+","+tri1.getC()+"的三角形,面积为:"+tri1.area());
}else {
System.out.println("边长为:"+tri1.getA()+","+tri1.getB()+","+tri1.getC()+"的三角形,能构成三角形!");
}
Triangle tri2 = new Triangle(50,8,9);
if(tri2.isFlag()) {
System.out.println("边长为:"+tri2.getA()+","+tri2.getB()+","+tri2.getC()+"的三角形,面积为:"+tri2.area());
}else {
System.out.println("边长为:"+tri2.getA()+","+tri2.getB()+","+tri2.getC()+"的三角形,不能构成三角形!");
}
}
}
4.测试结果:
边长为:3.0,4.0,5.0的三角形,面积为:6.0
边长为:50.0,8.0,9.0的三角形,不能构成三角形!