代码改变世界

第六次实训作业

2019-06-09 21:25  ~何处不相逢~  阅读(209)  评论(0编辑  收藏  举报

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

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

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

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

import java.util.Scanner;
public class YC {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入除数:");
        int a;
        a = input.nextInt(); 
        System.out.println("请输入被除数:");
        int b;
        b = input.nextInt();
        int result = 0;
        try {
            result=a / b;
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } finally {
            System.out.println("异常处理");
        }
        System.out.println(result);
        
    }}
  1. 编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。

代码为

import java.util.Scanner;

public class HB {
 double r;
 public static void main(String[] args){
  HB a1=new HB();
  Scanner rd=new Scanner(System.in);
  try{
   System.out.print("请输入半径");
   a1.r=rd.nextDouble();
   double s=a1.r*a1.r*3.14;
   System.out.println("圆的面积为"+s);
  }catch(Exception e){
  }
  finally{
   System.out.println("请输入正确的半径");
   Scanner re=new Scanner(System.in);
   a1.r=re.nextDouble();
   double s=a1.r*a1.r*3.14;
   System.out.print("圆的面积为"+s);
  
 }
}
3.为类的属性“身份证号码.id”设置值,当给的的值长度为18时,赋值给id,当值长度不是18时,抛出IllegalArgumentException异常,然后捕获和处理异常,编写程序实现以上功能。

代码为:

package 第六次;

import java.io.IOException;
import java.util.Scanner;
public class ID {
String ID;
String IDD;
static void pop(String IDD,String ID) throws IOException {
int n=IDD.length();
if(n==18) {
ID=IDD;
System.out.println("输入正确");
}
}
public static void main(String[] args) {
ID a1=new ID();
Scanner rd=new Scanner(System.in);
System.out.println("请输入身份证信息:");
a1.idd=rd.next();
try {
pop(a1.IDD,a1.ID);
}catch(IOException e) {
System.out.println(e.getMessage());
}
finally {
System.out.println("身份证信息输入错误");
}
}
}