Java程序设计精编教程(8.5上机实践)

实验目的

掌握使用try-catch语句

实验要求

车站检查危险品,如果发现危险品会发出警告。程序模拟设备发现危险品。

程序代码

class Goods{
	boolean isDanger;
	String name;
	Goods(String name){
		this.name = name;
	}
	public void setIsDanger(boolean boo) {
		isDanger = boo;
	}
	public String getName() {
		return name;
	}
}

class DangerException extends Exception{
	String message;
	public DangerException() {
		message = "危险品!";
	}
	public void toShow() {
		System.out.printf(message+" ");
	}
}

class Machine{
	public void checkBag(Goods goods) throws DangerException{
		if(goods.isDanger) {
			DangerException danger = new DangerException();
			//抛出danger
			throw(danger);
		}
	}
}

public class Check {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Machine machine = new Machine();
		Goods apple = new Goods("苹果");
		apple.setIsDanger(false);
		Goods explosive = new Goods("炸(敏感词)药");
		explosive.setIsDanger(true);
		try {
			machine.checkBag(explosive);
			System.out.println(explosive.getName()+"检查通过");
		} catch (DangerException e) {
			// TODO: handle exception
			//e调用toShow()方法
			e.toShow();
			System.out.println(explosive.getName()+"被禁止!");
		}
		try {
			machine.checkBag(apple);
			System.out.println(apple.getName()+"检查通过");
		} catch (DangerException e) {
			// TODO: handle exception
			e.toShow();
			System.out.println(apple.getName()+"被禁止!");
		}
	}
}

posted @ 2022-05-27 14:46  七色彩虹k  阅读(515)  评论(0)    收藏  举报