实训作业6

1. 编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:

²  在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;

²  在catch语句块中,捕获被0除所产生的异常,并输出异常信息;

²  在finally语句块中,输出一条语句。

package trouble;
import java.util.*;
public class ExceptionTest {
    public static void main(String[] args) {
        int a,b;
        int c=0;
        Scanner a1 = new Scanner(System.in);
        System.out.println("请输入除数");
        a = a1.nextInt();
        System.out.println("请输入被除数");
        b = a1.nextInt();
        try{
             c=a/b;
        }catch(ArithmeticException e){
            e.printStackTrace();
            System.out.println("异常");
        }finally{
            System.out.println("商:"+c);
            System.out.print("program over");
        }    
    }
}
       

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

package trouble;
import java.util.*;
public class circle {
    public static void main(String[] args) {
        double r;
        double s=0;
        Scanner x = new Scanner(System.in);
        System.out.print("输入半径");
     try{
         r = x.nextDouble();
          s=r*r*3.14;
    }catch(InputMismatchException e){
        e.printStackTrace();
        System.out.println("输入类型异常");
    }finally{
        System.out.println("圆的面积为"+s);    
        System.out.print("program over");
    }    
 }
}

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

public class Test {
    private String id;// 身份证号码的长度应为18
    public void setId(String id){
        if (id.length() == 18) {                //判断身份证号码的长度是否为18
            this.id = id;
        } else {
            throw new IllegalArgumentException("参数长度应为18!");    //抛出异常
        }
    }
    
    public static void main(String[] args) {
        Test  te = new Test ();
        try {
            te.setId("0123456789123456789");
        } catch (IllegalArgumentException ie) {        //捕获和处理异常
            System.out.println(ie.getMessage());
        }finally{
            System.out.println("结束");
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/CNblue392/p/10831041.html