已知三角形边长,求三角形面积

利用海伦公式求面积:
在这里插入图片描述

1.编写三角形类

package com.sanj.bean;

import com.sanj.exception.NotSanjiaoException;

import java.math.BigDecimal;

public class Sanj {

     private int x;
	    private int y;
	    private int z;

	    public Sanj() {
	    }

	    public Sanj(int x, int y, int z) {
	        this.x = x;
	        this.y = y;
	        this.z = z;
	    }

	    /**
	     * 获取三角形面积
	     * @return
	     */
	    public double getArea(){
	        //利用海伦公式求三角形面积
	        BigDecimal bigDecimal1 = new BigDecimal((this.x+this.y+this.z));
	        BigDecimal bigDecimal2 = new BigDecimal(2);
	        double p = bigDecimal1.divide(bigDecimal2, BigDecimal.ROUND_HALF_UP).doubleValue();
	        double area = Math.sqrt(p * (p - this.x) * (p - this.y) * (p - this.z));
	        return area;
	    }

	    /**
	     * 展示三角形边长
	     */
	    public void showInfo(){
	        System.out.println("三角形信息:");
	        System.out.println("x边:" + this.x + " y边:" + this.y + " z边:" + this.z );
	    }

	    /**
	     * 检查三边是否能组成三角形
	     */
	    public void check() throws NotSanjiaoException {
	        //校验三条边长非负数
	        if (this.x <= 0 || this.y <= 0 || this.z <= 0)
	            throw new NotSanjiaoException("x边:" + this.x + " y边:" + this.y + " z边:" + this.z + " 不能构成三角形");

	        //任意两边之和大于第三边
			if ((this.x + this.y) <= this.z || (this.x + this.z) <= this.y || (this.y + this.z) <= this.x)
				throw new NotSanjiaoException("x边:" + this.x + " y边:" + this.y + " z边:" + this.z + " 不能构成三角形");
			//任意两边之差小于第三边
			if ((this.x - this.y) >= this.z || (this.x - this.z) >= this.y || (this.y - this.z) >= this.x)
				throw new NotSanjiaoException("x边:" + this.x + " y边:" + this.y + " z边:" + this.z + " 不能构成三角形");
		}
}


2.编写自定义异常

package org.example.exception;
	
	/**
	 * 自定义异常类
	 * 三边不能组成三角形异常
	 */
	public class NotSanjiaoException extends Exception{
	
	    public NotSanjiaoException() {
	
	    }
	
	    public NotSanjiaoException(String message) {
	        super(message);
	    }
	
	
	
	}

3.测试

package org.example;

import org.example.bean.Sanj;
import org.example.exception.NotSanjiaoException;

import java.util.Scanner;

public class Test {
    public static void main(String[] args) throws NotSanjiaoException {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入第一条边边长:");
        int x = sc.nextInt();
        System.out.println("输入第二条边边长:");
        int y = sc.nextInt();
        System.out.println("输入第三条边边长:");
        int z = sc.nextInt();
        Sanj sanj = new Sanj(x,y,z);
        sanj.check();
        sanj.showInfo();
        double area = sanj.getArea();
        System.out.println("三角面积:"+area);
    }

}