12.三角形的三個邊為 a、b、c,請判斷是否為正三角形,並利用try-catch捕捉自訂的例外,這些例外由 triangle()拋出。
public class App13_12 { public static void main(String[] args) { try { Triangle t = new Triangle(); t.triangle(5, 2, 2); } catch (NotTriangle e) { System.out.println(e.getMessage()); } catch (EquilateralTriangle e) { System.out.println(e.getMessage()); } catch (NotEquilateralTriangle e) { System.out.println(e.getMessage()); } } } class NotTriangle extends Exception { public NotTriangle(int a, int b, int c) { super("不構成三角形"); } } class EquilateralTriangle extends Exception { public EquilateralTriangle(int a, int b, int c) { super("這是正三角形"); } } class NotEquilateralTriangle extends Exception { public NotEquilateralTriangle(int a, int b, int c) { super("這不是正三角形"); } } class Triangle { public void triangle(int a, int b, int c) throws NotTriangle, EquilateralTriangle, NotEquilateralTriangle { if ((a + b) < c || (a + c) < b || (b + c) < a) { throw new NotTriangle(a, b, c); } else if (a == b && b == c && c == a) { throw new EquilateralTriangle(a, b, c); } else { throw new NotEquilateralTriangle(a, b, c); } } }
沒有留言:
張貼留言