完成下列代码public class Goods { boolean isDanger; private String name; public void setIsDanger(boolean boo) { isDanger = boo; } public boolean isDanger() { return isDanger; } public void setName(String s) { name = s; } public String getName() { return name; }}DangerException.javapublic class DangerException extends Exception { String message; public DangerException() { message = "危险品!"; } public void toShow() { System.out.print(message+" "); }}Machine.javapublic class Machine { boolean isDanger; String name; public void setIsDanger(boolean boo) { isDanger = boo; } public boolean checkBag () //【代码0】声明异常 { DangerException danger=new DangerException() ; 【代码1】 //抛出danger }Check.javapublic class Check { public static void main(String args[]) { Machine machine = new Machine(); String name[] ={"苹果","炸药","西服","硫酸","手表","硫磺"}; Goods [] goods = new Goods[name.length]; //检查6件物品 for(int i= 0;i<name
时间: 2024-04-06 16:33:23 浏览: 137
.length;i++) { goods[i] = new Goods(); goods[i].setName(name[i]); if(i == 1 || i == 3 || i == 5) { goods[i].setIsDanger(true); machine.setIsDanger(true); } else { goods[i].setIsDanger(false); } try { boolean isDangerous = machine.checkBag(goods[i]); if(isDangerous) { System.out.println(goods[i].getName() + "是危险品!"); } else { System.out.println(goods[i].getName() + "是安全品!"); } } catch(DangerException e) { e.toShow(); System.out.println(goods[i].getName() + "是危险品!"); } } }}
其中【代码0】处需要声明DangerException异常,代码1处需要抛出DangerException异常。代码如下:
public boolean checkBag() throws DangerException {
if(isDanger) {
throw new DangerException();
}
else {
return false;
}
}
阅读全文