11.1第十週java作業

上機練習題——異常處理

課堂練習1:

寫一個方法void triangle(int a,int b,int c),判斷三個參數是否能構成一個三角形。如果不能則拋出異常IllegalArgumentException,顯示異常信息:a,b,c “不能構成三角形”;如果可以構成則顯示三角形三個邊長。在主方法中得到命令行輸入的三個整數,調用此方法,並捕獲異常。

代碼如下:

 Triangle類:

public class Triangle {
int a,b,c;
void judge(int a,int b,int c)  
    {  try{
        if((a+b>c)&&(b+c>a)&&(a+c>b))  
        {  
            System.out.printf("三角形的三邊是%d,%d,%d\n",a,b,c);  
        }  
        else  
        {  
            throw new IllegalArgumentException("abc不能構成三角形。");  
        }  }
        catch(IllegalArgumentException e)
        {
        e.getMessage();
        e.printStackTrace(); 
        }
    } 
}

測試類:

import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Triangle s=new Triangle();
Scanner in=new Scanner(System.in);
System.out.println("請輸入三角形的三邊長:");
int a,b,c;
a=in.nextInt();
b=in.nextInt();
c=in.nextInt();
s.judge(a, b, c);
}
}

測試結果:



課堂練習2:

從命令行輸入5個整數,放入一整型數組,然後打印輸出。要求:

如果輸入數據不爲整數,要捕獲輸入不匹配異常,顯示“請輸入整數”;如果輸入數據多餘5個,捕獲數組越界異常,顯示“請輸入5個整數”。

無論是否發生異常,都輸出“感謝使用本程序!”

 package j1101;
import java.util.*;
public class TestArrayException {
public static void main(String[] args) {
int a[] = new int[5];
System.out.println("請輸入5個數:");
System.out.println("最後輸入一個非數字結束輸入操作。");
Scanner in = new Scanner(System.in);
try{
int i = 0;
while(in.hasNextDouble()){     
a[i] = in.nextInt();
i++;
}
if(i<5)
throw new ArrayIndexOutOfBoundsException();
for(int j=0;j<5;j++)
System.out.print(a[j]+"  ");
System.out.println();
}catch(InputMismatchException e1){
System.err.println("請輸入整數作爲數組元素!");
e1.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e2){
System.err.println("請輸入5個數!");
e2.printStackTrace();
}finally{
System.out.print("感謝使用本程序!");
}

}

}

測試結果:


數字異常:


多於五個數:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章