Java基础---异常---练习

本文介绍了一个用于计算三角形面积的Java程序,并详细解释了如何处理输入参数导致的三角形无法形成的异常情况。
package com.train;
import java.lang.Math;
/********************
 * java.lang.Object
        java.lang.Math
 * static double sqrt(double a)---返回正确舍入的 double 值的正平方根。 
 * ******************/


class NoSanjiaoException extends RuntimeException{
    NoSanjiaoException(String msg) {
        super(msg);
    }
}

public class ExceptionTest {

    public static void main(String[] args) {
        
        Sanj sanj = new Sanj(10,20,30);
        
        System.out.println("This Sanj' area is  "+sanj.getArea());
        sanj.showInfo();
    }
}

class Sanj{
    private double x = 0;
    private double y = 0;
    private double z = 0;
    private double cirLength = 0;
    
    Sanj(double argX ,double argY, double argZ) throws NoSanjiaoException{
        this.x = argX;
        this.y = argY;
        this.z = argZ;
        this.cirLength = this.x + this.y +this.z;
        if(x+y<=z||x+z<=y||y+z<=x){
            throw new NoSanjiaoException("此三边无法构成三角形!");
        }
    }
    
    public void showInfo(){
        System.out.println("Sanj' x = "+this.x+"; y = "+this.y+"; z = "+this.z);
    }
    
    public double getArea(){
        return Math.sqrt(cirLength*(cirLength-x)*(cirLength-y)*(cirLength-z));
    }
}

:console:

image

转载于:https://www.cnblogs.com/plant/p/4647993.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值