Java练习--异常(8)

来源:互联网 发布:青蛙城 知乎 编辑:程序博客网 时间:2024/06/15 13:07

课堂练习1:

写一个方法void triangle(int a,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:a,b,c “不能构成三角形”;如果可以构成则显示三角形三个边长。在主方法中得到命令行输入的三个整数,调用此方法,并捕获异常。
两边之和大于第三边:a+b>c
两边之差小于第三边:c-a

package 异常;import java.util.Arrays;import java.util.InputMismatchException;import java.util.Scanner;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+"不能构成三角形");        }    }}

这里写图片描述
这里写图片描述

课堂练习2:

从命令行输入5个整数,放入一整型数组,然后打印输出。要求:
如果输入数据不为整数,要捕获输入不匹配异常,显示“请输入整数”;如果输入数据多余5个,捕获数组越界异常,显示“请输入5个整数”。
无论是否发生异常,都输出“感谢使用本程序!”

package 异常;import java.util.InputMismatchException;import java.util.Scanner;public class TestArray {    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("感谢使用本程序!");        }    }}

这里写图片描述

原创粉丝点击