java第5次作业(1)

来源:互联网 发布:csdn 算法岗面试 编辑:程序博客网 时间:2024/05/17 07:16

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

import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws Exception {
int shuzu[];
shuzu =new int[3];
System.out.println("请输入数值:");
Scanner a=new Scanner(System.in);
int a1=a.nextInt();
Scanner b=new Scanner(System.in);
int a2=a.nextInt();
Scanner c=new Scanner(System.in);
int a3=a.nextInt();
shuzu[0]=a1;shuzu[1]=a2;shuzu[2]=a2;
Arrays.sort(shuzu);
PrintCourse  t=new PrintCourse ();
try
{
t.triangle(a1, a2, a3);
  
}
catch(IllegalArgumentException e){
System.err.println("不能构成三角形");
e.printStackTrace();
}
catch(InputMismatchException e1){
System.err.println("输入数据类型不匹配");
e1.printStackTrace();
}
finally{
System.out.print("感谢使用本程序!");
}}
}


import java.util.InputMismatchException;
public class PrintCourse {
public void triangle(int a,int b,int c ) throws Exception 
{
if((a+b>c)&&(c-a<b))
{
System.out.println("可以构成三角形");
}
else 
{
throw new IllegalArgumentException("不能构成三角形");
 
}
}
}



总结:输入数据的不匹配的  异常处理不能显示   不是很懂...

 记住  throws throw的区别

会使用try catch finally的用法

原创粉丝点击