Java实验报告六
Java实验报告六
一、题目
二、实验代码
public class DangerException extends Exception {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public DangerException(String m) {
message = m + "为危险物品!";
}
public void toShow() {
System.out.println(message);
}
}
public class Goods {
private boolean isDanger;
private String name;
public void setisDanger(boolean isDanger) {
this.isDanger = isDanger;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isDanger() {
return isDanger;
}
}
public class Machine {
public void CheckBag(Goods goods) throws DangerException {
if (goods.isDanger()) {
throw new DangerException(goods.getName());
} else {
System.out.println(goods.getName() + "为非危险物品检查通过");
}
}
}
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Machine m = new Machine();
Goods goods = new Goods();
Scanner scanner = new Scanner(System.in);
for (int i = 0; i < 10; i++) {
String name = scanner.next();
goods.setName(name);
if (goods.getName().equals("毒品") || goods.getName().equals("刀具") || goods.getName().equals("汽油")
|| goods.getName().equals("枪")) {
goods.setisDanger(true);
} else {
goods.setisDanger(false);
}
try {
m.CheckBag(goods);
} catch (DangerException e) {
e.toShow();
}
}
}
}
三、运行结果截图