第六次上机作业

  1. 编写一个类ExceptionTest,在main方法中使用try-catch-finally语句结构实现:
    在try语句块中,编写两个数相除操作,相除的两个操作数要求程序运行时用户输入;
    在catch语句块中,捕获被0除所产生的异常,并输出异常信息;
    在finally语句块中,输出一条语句。
    import java.util.*;
    public class ExceptionTest {
    public static void main(String args[]){
    Scanner rd=new Scanner(System.in);

//ExceptionTest s1=new ExceptionTest();
//ExceptionTest s2=new ExceptionTest();
int a,b;
int c=0;
System.out.print("输入被除数:");
a=rd.nextInt();
System.out.print("输入除数:");
b=rd.nextInt();
try{
c=b/a;
}catch(Exception e){
System.out.println("除数不能为0");
}finally{
System.out.print("over");
}
}
}

  1. 编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。
    import java.util.*;
    public class yuan {
    public static void main(String args[]){
    Scanner rd=new Scanner(System.in);
    double r;
    System.out.print("输入圆的半径:");
    try{
    r=rd.nextDouble();
    }catch(InputMismatchException e){
    e.printStackTrace();
    System.out.print("要输入一个double型数据");
    }
    }
    }

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

package zwzw;
import java.util.*;
public class IDID {
public static void zw(int l,String ID)throws IllegalArgumentException {
if(l==18) {
System.out.print("身份证为:"+ID);
}else{
System.out.print("输入错误");
}
}
public static void main(String[] args) {
String ID;
Scanner id=new Scanner(System.in);
System.out.print("输入身份证号:");
ID=id.next();
int l=ID.length();
try {
zw(l,ID);
}catch(IllegalArgumentException e) {
e.printStackTrace();
System.out.print("错误!!");
}
}
}

猜你喜欢

转载自www.cnblogs.com/isudh5554537/p/10830707.html