JAVA程序设计第六次作业

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

public class id {
String a;
public void setId(String id){
if (id.length() == 18) {
this.a = a;
} else {
throw new IllegalArgumentException("身份证号码长度应为18!");
}
}

public static void main(String[] args) { id ac = new id (); try { ac.setId("0123456789123456789"); } catch (IllegalArgumentException ie) { System.out.println(ie.getMessage()); } }

}

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

import java.util.;
public class yuan {
public static void main(String[] args){
double a,p=3.14f,s=0;
Scanner sc = new Scanner(System.in);
try{
a=sc.nextDouble();
s=aa*p;
}
catch(InputMismatchException e){

        System.out.print("输入错误!"); } System.out.print(s); }

}

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

import java.util.*;
public class take {
public static void main(String[] args){

    int a,b,c=0; Scanner ac= new Scanner(System.in); System.out.print("请输入被除数:"); a=ac.nextInt(); System.out.print("请输入除数:"); b=ac.nextInt(); try{ c=a/b; } catch(ArithmeticException e){ System.out.print("除数不能为0!"); } System.out.print("\n"); System.out.print(c); }

}

猜你喜欢

转载自www.cnblogs.com/abcd609553/p/11139863.html