Java基础学习——异常机制与集合的结合练习

Java基础学习——异常机制与集合的结合练习

------模块功能说明:本模块模拟在一组产品中检测出违禁品

------采用技术手段:Java自定义异常、ArrayList 的转换和各类方法

------模块代码:

------自定义异常类MyException.class:

import java.util.ArrayList;

/**
 * @Author: HeSenBai
 * @Date: 11:15
 */
public class MyException extends Exception{
    ArrayList<String> contraband;
    // 构造方法接收传入的违禁品名单
    public MyException(ArrayList<String> message) {
        this.contraband = message;
    }
    @Override
    @SuppressWarnings("all")
    public String toString() {
        // 从 ArrayLis类型的contraband(违禁品)转换成String 字符串类型 返回;通过String.join方法
        return  String.join("、",this.contraband);
    }
}

------主类Test.class:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
/**
 * @Author: HeSenBai
 * @Date: 11:20
 */
public class Test {
    public static void Detect(ArrayList products,String[] contraband) throws MyException{
        Iterator iterator = products.iterator();
        ArrayList<String> Detected_contraband = new ArrayList<String>();
        // 设置flag标记 查看是否检测出违禁品,如果不适用flag标记,检测出违禁品就直接抛出异常了,无法检测出多个违禁品。使用flag后,将检测结果存放在(Detected_contraband)已检测违禁品中,可以实现多个违禁品和产品的匹对。
        boolean flag = false;
        while (iterator.hasNext()) {// 创建产品arraylist的迭代器来遍历与违禁品字符串数组比较
            Object obj =  iterator.next();
            for (String ctemp : contraband) {
                if (obj.equals(ctemp)){ // 检测出违禁品,flag 置 true
                    flag = true;
                    Detected_contraband.add(ctemp);
                 }
            }
        }
        if (flag == false) {
            System.out.println("未发现违禁品");
        }else {
            throw new MyException(Detected_contraband);
        }
    }

    public static void main(String[] args) {
        ArrayList products = new ArrayList();
        System.out.println("请输入受检查产品名单: ");
        Scanner sc = new Scanner(System.in);
        String s = sc.nextLine();
        // 将接收的检查名单 按照空格进行分割,得到String[]
        for (String temp : s.split(" ")) {
        // 采用 list.add 方法来动态地存放产品。
            products.add(temp);
        }
        System.out.println("请输入违禁品名称:");
        String s1 = sc.nextLine();
        String[] contraband = s1.split(" ");
        try {
            // 将受检查产品名单和违禁品名单进行比对,比对成功后发出异常,进行警告
            Detect(products,contraband);
        } catch (MyException e) {
            System.out.println("! 发现违禁品:" + e);
        } finally {
            sc.close();
        }
    }
}

------程序运行:

请输入受检查产品名单: 
小刀 香蕉 手机 相机 毒品 电脑 酒精 
请输入违禁品名称:
小刀 毒品 酒精
! 发现违禁品:小刀、毒品、酒精

-------运行结果图:

ICzrgU.png

posted @ 2021-11-01 19:18  hesenbai  阅读(44)  评论(0编辑  收藏  举报