1.定义一个Computer类,有属性private int state 表示为状态码,有2个方法,一个是run()方法,当state 为1时,在方法里正常显示“电脑成功运行”,当state 为2..

import java.util.Scanner;

class LanPIngException extends Exception {
    public LanPIngException() {
    }

    public LanPIngException(String message) {
        super(message);
    }
}

class MaoYanException extends Exception {
    public MaoYanException() {
    }

    public MaoYanException(String message) {
        super(message);
    }
}

class NoPlanException extends Exception {


    public NoPlanException() {
    }

    public NoPlanException(String message) {
        super(message);
    }
}

class Computer {
    int state;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
    }

    void run() throws LanPIngException, MaoYanException {
        if (state == 1)
            throw new LanPIngException("蓝屏啦");
        else if (state == 2)
            throw new MaoYanException("冒烟啦,废啦");
        else
            System.out.println("电脑运行正常,老师正常上课");
    }

    void reset() {
        System.out.println("电脑重启" + "\n");
        state = 0;
    }
}

class Teacher {
    private String name;
    private Computer cmpt;


    public Teacher(String name) {
        this.name = name;
    }


    public void attendClass() throws NoPlanException {
        cmpt = new Computer();
        int i1 = ((int) (Math.random() * 3) + 1);
        cmpt.setState(i1);
        try {
            System.out.println("讲课");
            cmpt.run();
        } catch (MaoYanException e) {
            e.printStackTrace();
            throw new NoPlanException("上课无法继续,因为电脑冒烟了,需要进行修理");
        } catch (LanPIngException e) {

            System.out.println("电脑蓝屏了");
            cmpt.reset();
            attendClass();
        }
    }
}

class ExceptionDemo {
    public static void main(String[] args) throws LanPIngException, MaoYanException, NoPlanException {
        Teacher t = new Teacher("hl");
        System.out.println("请输入你先尝试的次数");
        Scanner in = new Scanner(System.in);
        int i1 = in.nextInt();
        for (int i = 0; i < i1; i++) {
            t.attendClass();
        }

    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值