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

avatar 2017年04月26日10:45:10 1 3942 views
博主分享免费Java教学视频,B站账号:Java刘哥
有一个圆形和长方形。 都可以获取面积,对于如果如果出现非法值,视为是获取面积出现问题。 问题通过异常来表示。 现在对这个程序进行基本设计
  代码如下
  1. package com.liuyanzhao;
  2. class NoValueException extends RuntimeException {
  3.     NoValueException (String message) {
  4.         super(message);
  5.     }
  6. }
  7. interface Shape{
  8.     void getArea();
  9. }
  10. class Rec implements Shape {
  11.     private int len,wid;
  12.     Rec(int len,int wid) {
  13.         if(len<=0 || wid<=0) {
  14.             throw new NoValueException("长宽存在非法值");
  15.         }
  16.         this.len = len;
  17.         this.wid = wid;
  18.     }
  19.     public void getArea() {
  20.         System.out.println("长方形面积:"+len*wid);
  21.     }
  22. }
  23. class Circle implements Shape {
  24.     private int radius;
  25.     public static final double PI = 3.14;
  26.     Circle(int radius) {
  27.         if(radius<=0) {
  28.             throw new NoValueException("半径长度非法");
  29.         }
  30.         this.radius = radius;
  31.     }
  32.     public void getArea() {
  33.         System.out.println("圆形面积:"+radius*radius*PI);
  34.     }
  35. }
  36. public class ExceptionDemo1 {
  37.     public static void main(String[] args) {
  38.         Rec r = new Rec(34);
  39.         r.getArea();
  40.         Circle c = new Circle(-8);
  41.         c.getArea();
  42.     }
  43. }
运行结果:   本文永久更新地址:http://liuyanzhao.com/3356.html 转载请注明    
  • 微信
  • 交流学习,有偿服务
  • weinxin
  • 博客/Java交流群
  • 资源分享,问题解决,技术交流。群号:590480292
  • weinxin
avatar

发表评论

avatar 登录者:匿名
匿名评论,评论回复后会有邮件通知

  

已通过评论:1   待审核评论数:0
  1. avatar 星空游戏

    厉害了!