1.編一個程式Average.java,輸入5個正整數并求其平均數。
要求:
(1) 自定義一個異常類NotPositiveException,繼承自Exception。當輸入是負整數或零時,生成并抛出一個這種異常的對象;
(2) 程式能夠捕獲NumberFormatException、ArithmeticException、NotPositiveException,如果有其它異常也能使程式正常結束不被中斷(提示:需要捕獲Exception異常);
package nine;
import java.util.*;
import java.lang.*;
import java.io.*;
public class one1 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int[] a = new int[5];
int sum = 0;
float avg = 0;
for (int j = 0; j < 5; j++) {
try {
a[j] = s.nextInt();
if (a[j] <= 0) {
throw new NotPositiveException(a, j);
}
System.out.println("輸入的整數為:" + a[j]);
sum = sum + a[j];
} catch (NotPositiveException e) {
System.out.println(e.toString());
j--;
}catch (ArithmeticException e) {
//System.out.print(e.getMessage());
System.out.print("錯誤1");
e.printStackTrace();
s.next();
j--;
}catch (NumberFormatException e) {
//System.out.print(e.getMessage());
e.printStackTrace();
System.out.print("錯誤2");
s.next(); //清空緩沖區
j--;
}
catch (Exception e){
// System.out.print(e.getMessage());
e.printStackTrace();
System.out.print("錯誤");
s.nextLine();
j--;
}
}
avg=(float)sum/5;
System.out.println("總數:"+sum);
System.out.println("平均數:"+avg);
}
}
class NotPositiveException extends Exception{
int a[]=new int[5];int i;
NotPositiveException(int[] a,int i){
this.i=i;
this.a[i]=a[i];
}
public String toString(){
return a[i]+"是為0或者負數";
}
}