A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© sunsteam 中级黑马   /  2015-8-20 10:25  /  443 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

  1. /**
  2. 一个长方形和一个圆形, 求面积. 如果如果参数出现负数,则认为是异常, 运算无结果
  3. */

  4. class AreaException extends RuntimeException  //继承运行时错误的自定义异常, 面积异常
  5. {
  6.         AreaException (String msg)
  7.         {        
  8.                 super(msg);
  9.         }
  10. }

  11. abstract class Shape //长方形和圆形父类, 包含求面积的抽象方法
  12. {
  13.         abstract void getarea();
  14. }

  15. class Rectangle extends Shape //长方形类
  16. {
  17.         private int len,wid;
  18.         Rectangle (int len, int wid)  //构造函数中为长方形对象赋值长和宽特性
  19.         {
  20.                 if (len<=0 || wid<=0)
  21.                 {
  22.                         throw new AreaException("长宽参数不正确,面积无法运算"); // 如果参数不正确, 则抛出运行时异常对象
  23.                 }
  24.                 this.len= len;
  25.                 this.wid= wid;
  26.         }
  27.         void getarea()
  28.         {
  29.                 System.out.println(len*wid);        
  30.         }
  31. }

  32. class Circle extends Shape  //圆形类
  33. {
  34.         private int radius;
  35.         Circle(int radius)
  36.         {
  37.                 if(radius <= 0)   //构造函数中为圆形对象赋值半径特性
  38.                         throw new AreaException("半径参数不正确,面积无法运算");
  39.                 this.radius = radius;
  40.         }
  41.         void getarea()
  42.         {
  43.                 System.out.println(3.14*radius*radius);
  44.         }
  45. }


  46. class ExceptionTest
  47. {
  48.         public static void main(String[] args)
  49.         {
  50.                 Shape a = new Rectangle(2,5);
  51.                 a.getarea();
  52.                 a = new Circle(0);
  53.                 a.getarea();
  54.         }
  55. }
复制代码
自己写代码过程中犯的错误
1. 把abstract class 写成了abstract interface
2. 把创建对象
Shape a = new Rectangle(2,5);中的参数写到了调用方法a.getarea();中
3. throw new AreaException(); 语句里漏写new
4. AreaException (String msg) 语句漏写参数类型String


1 个回复

倒序浏览
风华正茂 来自手机 中级黑马 2015-8-20 12:28:41
沙发
谢谢楼主分享,楼主辛苦了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马