题目:
写一个方法void triangle(inta,int b,int c),判断三个参数是否能构成一个三角形。如果不能则抛出异常IllegalArgumentException,显示异常信息:a,b,c “不能构成三角形”;如果可以构成则显示三角形三个边长。在主方法中得到命令行输入的三个整数,调用此方法,并捕获异常。
a<b<c
两边之和大于第三边:a+b>c
两边之差小于第三边:c-a<a
主要代码:
public class sjx {
int a,b,c;
void triangle(int a,int b,int c)throws Exception{
this.a=a;
this.b=b;
this.c=c;
if(a+b>c||c-a<a){
System.out.println("构成三角形的三条边为:"+this.a+","+this.b+","+this.c);
}else{
throw new IllegalArgumentException();
}
}
}
public class Test {
public static void main(String[] args) {
int []s=new int[3];
System.out.println("请输入三条边:");
Scanner in=new Scanner(System.in);
try {
for(int i=0;i<s.length;i++){
if(in.hasNextInt())
s[i]=in.nextInt();
else
throw new InputMismatchException();
}
Arrays.sort(s);
sjx t=new sjx();
t.triangle(s[0], s[1], s[2]);
}catch(IllegalArgumentException e) {
System.err.println(s[0]+","+s[1]+","+s[2]+",不能构成三角形");
}catch(InputMismatchException e) {
System.err.println("请输入整数作为三角形的边长!");
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
运行图:
最后
以上就是落寞鸵鸟最近收集整理的关于java 三角形 异常处理的全部内容,更多相关java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复