上机练习题——异常处理

来源:互联网 发布:车座套什么材质好 知乎 编辑:程序博客网 时间:2024/06/05 11:44

课堂练习1

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

a<b<c

两边之和大于第三边:a+b>c

两边之差小于第三边:c-b<a

实现代码:

import java.util.Arrays;import java.util.InputMismatchException;import java.util.Scanner;public class CatchTriangle {public static void triangle(int a,int b,int c) throws IllegalArgumentException, InputMismatchException{int[] s=new int[3];s[0]=a;s[1]=b;s[2]=c;Arrays.sort(s);if((s[0]+s[1]>s[2])&&(s[2]-s[1]<s[0])){System.out.println("三角形的三边长分别为"+a+","+b+","+c);}else{throw new IllegalArgumentException();}}public static void main(String[] args) {// TODO Auto-generated method stubint 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("三条边长必须是整数");}catch (IllegalArgumentException e2) {// TODO: handle exceptionSystem.err.println(a+","+b+","+c+"不能构成三角形");}}}

运行结果:



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

import java.util.InputMismatchException;import java.util.Scanner;public class CatchArray {public static void main(String[] args) {// TODO Auto-generated method stubint a[]=new int[5];System.out.println("请输入5个数作为数组元素:");System.out.println("最后输入一个非数字结束输入操作。");Scanner in=new Scanner(System.in);try {int i=0;while(in.hasNextInt()){a[i]=in.nextInt();i++;}if(i>5){throw new ArrayIndexOutOfBoundsException();}for(int j=0;j<a.length;j++){System.out.print(a[j]+"");}}catch(InputMismatchException e1){System.err.println("请输入整数!");e1.printStackTrace();}catch (ArrayIndexOutOfBoundsException e2) {// TODO: handle exceptionSystem.err.println("请输入5个整数!");e2.printStackTrace();}finally{System.out.println("感谢使用本程序!");}}}

运行结果: