自定义异常处理机制
/*
1.編寫(xiě)應(yīng)用程序,從鍵盤輸入10個(gè)學(xué)生的數(shù)學(xué)成績(jī),統(tǒng)計(jì)及格人數(shù)、不及格人數(shù)、平均分。要求輸入的數(shù)學(xué)成績(jī)?cè)?~100之間
(設(shè)計(jì)一個(gè)自定義異常類NumberRangeException,當(dāng)輸入的成績(jī)不在0~100之間時(shí),拋出該異常類對(duì)象,程序中捕獲這個(gè)異常并作出相應(yīng)的處理)。?
*/
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("請(qǐng)輸入第"+(i+1)+"個(gè)同學(xué)的成績(jī):");
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("數(shù)值不在0~100之間");
}
}
System.out.println();
System.out.println("及格的人數(shù)為:"+m);
System.out.println("不及格的人數(shù)為:"+n);
System.out.println("平均成績(jī)?yōu)?"+sum/5);
}
public static void run(){
try
{
new ScannerDemo().num();
}
catch (NumberRangeException e)
{
e.printMsg();
}
}
public static void main(String[] args)?
{
run();
}
}
1.編寫(xiě)應(yīng)用程序,從鍵盤輸入10個(gè)學(xué)生的數(shù)學(xué)成績(jī),統(tǒng)計(jì)及格人數(shù)、不及格人數(shù)、平均分。要求輸入的數(shù)學(xué)成績(jī)?cè)?~100之間
(設(shè)計(jì)一個(gè)自定義異常類NumberRangeException,當(dāng)輸入的成績(jī)不在0~100之間時(shí),拋出該異常類對(duì)象,程序中捕獲這個(gè)異常并作出相應(yīng)的處理)。?
*/
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("請(qǐng)輸入第"+(i+1)+"個(gè)同學(xué)的成績(jī):");
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("數(shù)值不在0~100之間");
}
}
System.out.println();
System.out.println("及格的人數(shù)為:"+m);
System.out.println("不及格的人數(shù)為:"+n);
System.out.println("平均成績(jī)?yōu)?"+sum/5);
}
public static void run(){
try
{
new ScannerDemo().num();
}
catch (NumberRangeException e)
{
e.printMsg();
}
}
public static void main(String[] args)?
{
run();
}
}
轉(zhuǎn)載于:https://www.cnblogs.com/javaTest/archive/2012/04/24/2589477.html
總結(jié)
- 上一篇: C# 操作其他进程ListView
- 下一篇: 【转载】SDRAM时钟相移估算