- 自定义异常AreaException,表示计算面积出现异常。
- 定义接口方法getArea()抛出异常public double getArea() throws AreaException。
- 在实现类中具体抛出异常,例如圆桌半径小于0则抛出异常AreaException。
【输入形式】圆桌半径
【输出形式】圆桌面积或者异常
【样例输入】
10
【样例输出】
Area=314.0
【样例输入】
0
【样例输出】
Exception is: AreaException: Round table radius<=0
Area=0.0
import java.util.Scanner;
public class Test{
public static void main(String [] args){
Scanner sc = new Scanner(System.in);
double r = sc.nextDouble();
RoundTable t1=new RoundTable(3, 100, r);
System.out.println("Area=" + t1.getArea());
}
}
interface MoveAble{
public void move();
}
abstract class TableInfo implements MoveAble{
int legs;
int hight;
public TableInfo( int legs,int hight){
this.legs = legs;
this.hight = hight;
}
public void move(){
System.out.println("被人搬动了!");
}
}
interface CalculateAble{
public double getArea();
}
class RoundTable extends TableInfo implements CalculateAble{
private double r;
public RoundTable( int legs,int hight,double r){
super(legs,hight);
this.r=r;
}
public double getArea(){
double a=0;
try{
a=test(r);
}
catch(AreaException e){
System.out.println("Exception is: " + e);
}
return a;
}
private double test(double r) throws AreaException{
if (r<=0){
throw new AreaException("Round table radius<=0");
}
return 3.14*r*r;
}
}
class AreaException extends Exception{ // 此异常要强制处理
public AreaException(String msg)
{
super(msg); //调用父类构造
}
}
如果这份代码可以帮到你,代码书写让你明白了这道题目,希望你可以留言或点赞,告诉我你懂了就足够了,我想看到我是否真的帮助到了你,并以此作为我编码是否正确的参考之一,谢谢!最后真心希望你已经可以解决你遇到的问题!