第五次实训作业
1.编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
在finally语句块中,输出一条语句。
package ZGX.inherit; import java.util.*; public class ExceptionTest { public static void main(String[] args) { try { Scanner in=new Scanner(System.in); int x,y,z; System.out.print("请输入两个数:"); x=in.nextInt(); y=in.nextInt(); z=x/y; System.out.print("结果是:"); System.out.println(z); } catch(ArithmeticException e) { e.printStackTrace(); } finally { System.out.println(6666); } } }
2.编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。
package ZGX.Demo; import java.util.*; public class Area { public static void main(String[] args) { try { Scanner in=new Scanner(System.in); double s,r; System.out.print("请输入圆的半径:"); r=in.nextDouble(); s=r*r*3.14; System.out.println("圆的面积是:"+s); } catch(InputMismatchException e) { e.printStackTrace(); } }
3.为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。
package ZGX.inherit; class Person { private String name; private int age; private String id; public String getId() { return id; } public void setId(String id) throws IllegalArgumentException { if(id.length()!=18) { throw(new IllegalArgumentException()); } this.id = id; } } class IllegalArgumentException extends Exception { } public class ExceptionTest1 { public static void main(String[] args) { Person p1 = new Person(); Person p2 = new Person(); try { p1.setId("430223200010031111"); p2.setId("43654576345"); } catch (IllegalArgumentException e) { System.out.println("你输入的身份证长度有错误"); } } }
浙公网安备 33010602011771号