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.定义一个Computer类,有属性private int state 表示为状态码,有2个方法,一个是run()方法,当state 为1时,在方法里正常显示“电脑成功运行”,当state 为2..
最新推荐文章于 2023-07-20 01:16:17 发布