异常处理-三角形

来源:互联网 发布:购物app源码 编辑:程序博客网 时间:2024/06/07 23:54
import java.util.Arrays;  import java.util.Scanner;  import java.util.InputMismatchException;  public class TestTriangle {public static void triangle(int a, int b,int c) throws IllegalArgumentException, InputMismatchException{                     int x[] = new int[3];                  x[0] = a;                 x[1] = b;                  x[2] = c;                  Arrays.sort(x);                  if ((x[0]+x[1]>x[2])&&(x[2]-x[1]<x[0]))                      System.out.println("三角形的三边长为:"+a+","+b+","+c);                  else                      throw new IllegalArgumentException();              }                public static void main(String[] args) {                  int a=0, b=0, c=0;                  Scanner in = new Scanner(System.in);                  System.out.println("请分别输入三角形的三边长:");                  try{                    a = in.nextInt();                      b = in.nextInt();                      c = in.nextInt();                      triangle(a, b, c);                  }catch(InputMismatchException e1){                      System.err.println("请输入整数作为三角形的边长!");                      e1.printStackTrace();                  }catch(IllegalArgumentException e2){                      System.err.println(a+","+b+","+c+"不能构成三角形");                  }              }  }

原创粉丝点击