我是靠谱客的博主 舒适鱼,这篇文章主要介绍异常处理--三角形,现在分享给大家,希望可以做个参考。

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

复制代码
1
2
3
4
5
6
7
8
9
10
package test; public class Triangle{ public void triangle(int a,int b,int c)throws IllegalArgumentException{ if(a+b>c&&c-a<b) System.out.println("三角形的三个边长是:"+a+" "+b+"" + " "+c); else throw new IllegalArgumentException(); } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package test; import java.util.*; public class Application { public static void main(String[] args) { // TODO Auto-generated method stub try{ int i[]=new int[3]; System.out.println("请输入三角形的三条边"); Scanner input=new Scanner(System.in); i[0]=input.nextInt(); i[1]=input.nextInt(); i[2]=input.nextInt(); Arrays.sort(i);//系统自动按升序自动排列 //System.out.println(i[0]+i[1]+i[2]); Triangle t=new Triangle(); t.triangle(i[0],i[1],i[2]); } catch(ArrayIndexOutOfBoundsException a){ System.err.println("数组下标越界"); } catch(InputMismatchException e){ System.err.println("输入不符合实际情况,请输入数字作为三角形的边长"); e.printStackTrace(); } catch(IllegalArgumentException e){ System.err.println("不能构成三角形"); } catch(Exception e){ System.err.println("出现错误"); e.printStackTrace(); } } }

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

最后

以上就是舒适鱼最近收集整理的关于异常处理--三角形的全部内容,更多相关异常处理--三角形内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(47)

评论列表共有 0 条评论

立即
投稿
返回
顶部