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 @   七色彩虹k  阅读(492)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
点击右上角即可分享
微信分享提示