1. 程式人生 > 其它 >Java程式設計精編教程(8.5上機實踐)

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()+"被禁止!");
		}
	}
}