请按模板要求,将【代码】替换为Java程序代码。Goods.javapublic 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];
时间: 2024-04-06 14:33:22 浏览: 86
// Goods.java
public class Goods {
private 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.java
public class DangerException extends Exception {
private String message;
public DangerException() {
message = "危险品!";
}
public void toShow() {
System.out.print(message + " ");
}
}
// Machine.java
public class Machine {
private boolean isDanger;
private String name;
public void setIsDanger(boolean boo) {
isDanger = boo;
}
public boolean checkBag() throws DangerException { // 【代码0】声明异常
if(isDanger) {
throw new DangerException();
}
else {
return false;
}
}
}
// Check.java
public 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.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();
if(isDangerous) {
System.out.println(goods[i].getName() + "是危险品!");
}
else {
System.out.println(goods[i].getName() + "是安全品!");
}
}
catch(DangerException e) { // 【代码1】抛出DangerException异常
e.toShow();
System.out.println(goods[i].getName() + "是危险品!");
}
}
}
}
阅读全文