課堂練習1:
寫一個方法void triangle(int a,int b,int c),判斷三個參數是否能構成一個三角形。如果不能則拋出異常IllegalArgumentException,顯示異常信息:a,b,c “不能構成三角形”;如果可以構成則顯示三角形三個邊長。在主方法中得到命令行輸入的三個整數,調用此方法,並捕獲異常。
a<b<c
兩邊之和大於第三邊:a+b>c
兩邊之差小於第三邊:c-a<a
1.triangleTest.java
import java.util.Scanner;
public class triangleTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
System.out.print("請輸入第一條邊的邊長:");
int B1 = in.nextInt();
System.out.print("請輸入第二條邊的邊長:");
int B2 = in.nextInt();
System.out.print("請輸入第三條邊的邊長:");
int B3 = in.nextInt();
try {
triangle(B1,B2,B3);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
public static void triangle(int a,int b,int c) throws IllegalArgumentException{
if(a+b>c&&b+c>a&&a+c>b){
int s=a+b+c;
System.out.print("三角形的邊長是:"+s);
}
else
throw new IllegalArgumentException("不能構成三角形。");
}
}
2.運行截圖