练习题:
1.计算圆的面积,半径不能为零和负数
package com.oracle.Demo01; public class Demo02 { // 写一个计算圆的面积的方法,传一个半径,返回面积 public static void main(String[] args) { double s=0; s = area(-4); System.out.println(s); } public static double area(double r){ try { if(r<=0){ throw new RuntimeException(); //RuntimeException 运行异常,不会声明,不会处理异常,直接报错并且停止 } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } double s=Math.PI*r*r; return s; } }
2.求平均数,参数不能为负数
package com.oracle.Demo01; import java.util.Scanner; public class Demo03 { //现在要创建一个检测负数的异常类,如果是正数,则抛出异常 public static void main(String[] args){ /*double s=0; s = area(9); System.out.println(s);*/ //输入任意参数,求平均数 double s=avg(1,9,6,5,2); System.out.println(s); } public static double area(double r){ if(r<=0){ throw new FuShuException("你传了一个负数"); //报异常并传递自定义的字符串 } double s=Math.PI*r*r; return s; } //求平均数的方法 public static double avg(double...arr){ double sum=0; for(double i:arr){ if(i<0){ throw new FuShuException("参数为负数"); } sum=sum+i; } return sum/arr.length; } }
自定义FuShuExecption类:
package com.oracle.Demo01; //自定义类异常,继承自运行异常 public class FuShuException extends RuntimeException { FuShuException(String mes){ super(mes); } }
3.检测年龄不能为负数和大于200岁
测试类:
package com.oracle.Demo01; public class Demo04 { public static void main(String[] args) throws NoAgesException { method("阿易",110); } public static void method(String name,int age) throws NoAgesException{ Person p=new Person(name,age); if(p.getAge()<0||p.getAge()>200){ throw new NoAgesException("年龄数值非法"); } System.out.println(p.getName()+"..."+p.getAge()); } }
Person类:
package com.oracle.Demo01; public class Person { private String name; private int age; Person(){ } Person(String name,int age){ this.name=name; this.age=age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
自定义NoAgeExecption类:
package com.oracle.Demo01; public class NoAgesException extends Exception { NoAgesException(){ //声明父类的异常方法 super(); } NoAgesException(String mes){ super(mes); } }