自定义异常处理机制

/*
1.编写应用程序,从键盘输入10个学生的数学成绩,统计及格人数、不及格人数、平均分。要求输入的数学成绩在0~100之间
(设计一个自定义异常类NumberRangeException,当输入的成绩不在0~100之间时,抛出该异常类对象,程序中捕获这个异常并作出相应的处理)。 


*/
import java.util.*;
class NumberRangeException extends Exception{//必须继承父类Exception
NumberRangeException(String s){
super(s);
}
public void printMsg(){
System.out.println("exception="+this.getMessage());
this.printStackTrace();
System.exit(0);
}
}
class  ScannerDemo{
double[] a=new double[5];
int m=0;
int n=0;
int sum=0;
public void num() throws NumberRangeException{
Scanner s=new Scanner(System.in);
for(int i=0;i<a.length;i++){
System.out.print("请输入第"+(i+1)+"个同学的成绩:");
a[i]=s.nextDouble();
sum+=a[i];
if(a[i]>0&&a[i]<100){
if(a[i]>=60){
m++;//及格
}else{
n++;//不及格
}

}else{
throw new NumberRangeException("数值不在0~100之间");

}
}
System.out.println();
System.out.println("及格的人数为:"+m);
System.out.println("不及格的人数为:"+n);
System.out.println("平均成绩为:"+sum/5);
}
public static void run(){
try
{
new ScannerDemo().num();
}
catch (NumberRangeException e)
{
e.printMsg();
}


}
public static void main(String[] args) 
{
run();
}
}

posted on 2012-04-24 19:48  java课程设计  阅读(691)  评论(0编辑  收藏  举报

导航