程序实现的功能:
定义Circle类,包含成员变量半径r和计算面积的方法getArea()。自定义异常类,当半径小于0的时候抛出异常,计算圆面积,如有异常输出异常信息。
class Circle{
double r;
final double PI=3.14;
public Circle(double r) throws Exception {
if(r<0)
throw new Exception("半径不能小于0!!!");
else
this.r=r;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public double getPI() {
return PI;
}
public double getArea() {
return getPI()*getR()*getR();
}
}
public class Test5 {
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Scanner input=new Scanner(System.in);
double r=input.nextDouble();
Circle c1=new Circle(r);
try {
System.out.println(c1.getArea());
}
catch(Exception e) {
System.out.println(e.getMessage());
}
}
}