zoukankan      html  css  js  c++  java
  • 第六次上机作业

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

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

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

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

    代码:

    import java.util.Scanner;
    public class ExceptionTest {
     int a;
     int b;
     public static void main(String[] args) {
      ExceptionTest a1 = new ExceptionTest();
      Scanner rd=new Scanner(System.in);
      System.out.print("请输入第一个数");
      a1.a=rd.nextInt();
      System.out.print("请输入第二个数");
      a1.b=rd.nextInt();
      try{
       int c=a1.a/a1.b;
      }catch(ArithmeticException e){
       e.printStackTrace();
     }
      finally{
       System.out.print("除数不能为零");
      }
     }
    }
    运行结果:

    2. 编写一个应用程序,要求从键盘输入一个double型的圆的半径,计算并输出其面积。

    测试当输入的数据不是double型数据(如字符串“abc”)会产生什么结果,怎样处理。

    代码:

    import java.util.Scanner;
    public class round {
     double r;
     public static void main(String[] args){
      round a1=new round();
      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 class5;
    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("身份证信息输入错误");
    }
    }
    }

    运行结果:

  • 相关阅读:
    「学习笔记」杂项算法学习笔记
    「CF484E」Sign on Fence「整体二分」「线段树」
    「BZOJ 2653」middle「主席树」「二分」
    「BZOJ 5010」「FJOI 2017」矩阵填数「状压DP」
    jmeter阶梯式加压测试
    jmeter监控内存,CPU等方法
    jmeter 读取多个用户名并同时发
    APP性能测试工具
    Android--iOS抓取崩溃日志
    安装并使用PICT,生成测试用例
  • 原文地址:https://www.cnblogs.com/1121yjj/p/10831009.html
Copyright © 2011-2022 走看看