您的位置:首页 > 编程语言 > Java开发

Java求矩形面积和圆形面积的异常处理实例

2017-05-22 15:25 1101 查看
题目

有一个圆形和长方形。
都可以获取面积,对于如果如果出现非法值,视为是获取面积出现问题。
问题通过异常来表示。
现在对这个程序进行基本设计


代码如下

package com.liuyanzhao;
class NoValueException extends RuntimeException {
NoValueException (String message) {
super(message);
}
}
interface Shape{
void getArea();
}
class Rec implements Shape {
private int len,wid;
Rec(int len,int wid) {
if(len<=0 || wid<=0) {
throw new NoValueException("长宽存在非法值");
}
this.len = len;
this.wid = wid;
}
public void getArea() {
System.out.println("长方形面积:"+len*wid);
}
}
class Circle implements Shape {
private int radius;
public static final double PI = 3.14;
Circle(int radius) {
if(radius<=0) {
throw new NoValueException("半径长度非法");
}
this.radius = radius;
}
public void getArea() {
System.out.println("圆形面积:"+radius*radius*PI);
}
}
public class ExceptionDemo1 {
public static void main(String[] args) {
Rec r = new Rec(3, 4);
r.getArea();
Circle c = new Circle(-8);
c.getArea();
}
}


运行结果:



本文永久更新地址:http://liuyanzhao.com/3356.html

转载请注明
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: