如何编写和应用Java的自定义异常类
答案:1 悬赏:70 手机版
解决时间 2021-12-29 19:47
- 提问者网友:雾里闻花香
- 2021-12-29 07:14
如何编写和应用Java的自定义异常类
最佳答案
- 五星知识达人网友:慢性怪人
- 2021-12-29 08:28
// 给个例子你
class NotSanJException extends Exception{
public NotSanJException(String msg){
62616964757a686964616fe4b893e5b19e31333337613837super(msg);
}
}
public class SanJ {
private double x;
private double y;
private double z;
public SanJ(double x, double y, double z) throws NotSanJException{
if((x + y) <= z || (y + z) <= x || (z + x) <= y){
throw new NotSanJException("不能构成三角形.");
}else{
this.x = x;
this.y = y;
this.z = z;
}
}
public void outPut(){
System.out.println("三角形三条边为: x = " + this.x + ". y = " + this.y + ". z = " + this.z);
}
public void getArea(){
double p=(this.x + this.y + this.z) / 2;
System.out.println("三角形的面积为: " + String.format("%.3f", Math.sqrt(p*(p-x)*(p-y)*(p-z))));
}
public static void main(String[] args) {
try {
//SanJ sj1 = new SanJ(2.0, 3.0, 1.0);
SanJ sj2 = new SanJ(2.0, 3.0, 3.0);
sj2.outPut();
sj2.getArea();
} catch (NotSanJException e) {
// TODO: handle exception
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
class NotSanJException extends Exception{
public NotSanJException(String msg){
62616964757a686964616fe4b893e5b19e31333337613837super(msg);
}
}
public class SanJ {
private double x;
private double y;
private double z;
public SanJ(double x, double y, double z) throws NotSanJException{
if((x + y) <= z || (y + z) <= x || (z + x) <= y){
throw new NotSanJException("不能构成三角形.");
}else{
this.x = x;
this.y = y;
this.z = z;
}
}
public void outPut(){
System.out.println("三角形三条边为: x = " + this.x + ". y = " + this.y + ". z = " + this.z);
}
public void getArea(){
double p=(this.x + this.y + this.z) / 2;
System.out.println("三角形的面积为: " + String.format("%.3f", Math.sqrt(p*(p-x)*(p-y)*(p-z))));
}
public static void main(String[] args) {
try {
//SanJ sj1 = new SanJ(2.0, 3.0, 1.0);
SanJ sj2 = new SanJ(2.0, 3.0, 3.0);
sj2.outPut();
sj2.getArea();
} catch (NotSanJException e) {
// TODO: handle exception
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
推荐资讯