课堂练习1:
写一个方法void triangle(int a,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:a,b,c “不能构成三角形”;如果可以构成则显示三角形三个边长。在主方法中得到命令行输入的三个整数,调用此方法,并捕获异常。
(1)代码实现
- import java.util.*;
- public class triangleException {
-
- public void triangle(int a,int b,int c) throws IllegalArgumentException {
-
- if(a+b>c && c-a<b ) {
- System.out.printf("三角形的三边长分别是:%d%d%d",a,b,c);
- }
-
- else {
- throw new IllegalArgumentException("不能构成三角形");
- }
- }
- }
- import java.lang.reflect.Array;
- import java.util.*;
- public class test {
-
- public static void main(String[] args) {
-
- triangleException t=new triangleException();
- Scanner s=new Scanner(System.in);
-
- int n[]=new int[3];
- System.out.println("请输入三角形的三条边");
-
- for(int i=0;i<3;i++) {
- n[i]=s.nextInt();
- }
-
- Arrays.sort(n);
- try {
- t.triangle(n[0], n[1], n[2]);
- }catch(IllegalArgumentException e) {
- System.err.printf("长度为%d%d%d的三条边不能构成三角形",n[0],n[1],n[2]);
- }catch(InputMismatchException e) {
- System.err.println("三角形的边长应为整数");
- }
-
- }
-
- }
(2)运行结果

