第五次实训作业异常处理

1.编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
 在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
 在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
 在finally语句块中,输出一条语句。

复制代码
 1 package csh; 
 2 import java.util.*;
 3 public class ExceptionTest
 4 {
 5 
 6  public static void main(String[] args)
 7  {     
 8      try  
 9      {   
10          Scanner in=new Scanner(System.in); 
11          int x,y,z;
12          System.out.print("请输入两个数:");
13          x=in.nextInt(); 
14          y=in.nextInt();   
15          z=x/y; 
16          System.out.print("结果是:");
17          System.out.println(z); 
18          }     
19      catch(ArithmeticException e)     
20      {     
21          e.printStackTrace();   
22      }  
23      finally 
24      {   
25          System.out.println(6666); 
26      } 
27      }
28 
29 }
复制代码

2.编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。

复制代码
package csh;

import java.util.*;
public class Circle {
public static void main(String[]args) {
    double r;
    double s=0;
    Scanner sc=new Scanner (System.in);
    System.out.println("请输入圆的半径:");
    try {
        r=sc.nextDouble();
        s=r*r*3.14;
    }catch(InputMismatchException e){
        e.printStackTrace();
        System.out.println("输入类型异常");
    }finally {
        System.out.println("圆的面积为:"+s);
        System.out.println("PROGRAM OVER");
    }
}
}
复制代码

3.为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。

程序如下:

复制代码
 1 package csh;
 2 import java.util.*;
 3 public class Person 
 4 {
 5     String id;
 6     public void LengthJudge(String id) throws IllegalArgumentException
 7     {
 8         
 9         if(id.length()>18||id.length()<18)
10         {
11             throw new IllegalArgumentException("身份证号码长度不合法!");
12         }
13         else
14         {
15             System.out.println("长度合法!");
16         }
17          
18     }
19     public static void main(String[] args) 
20     {
21         Scanner sc=new Scanner(System.in);
22         Person p=new Person();
23         try
24         {
25             System.out.println("请输入身份证号码:");
26             p.id=sc.next();
27             p.LengthJudge(p.id);
28             
29         }
30         catch(IllegalArgumentException e)
31         {
32             System.out.println(e);
33         }
34         sc.close();
35     }
36 }
复制代码

 

posted @ 2019-05-16 20:18  陈思豪  阅读(198)  评论(0编辑  收藏  举报