内部类与异常类:实验2
class DangerException extends Exception{
String message;
public DangerException() {
this.message = "是危险品";
}
public void toShow() {
System.out.println(message);
}
}
class Good{
boolean isDanger;
String name;
public Good(boolean isDanger, String name){
this.isDanger = isDanger;
this.name = name;
}
public String get_name() {
return name;
}
}
class Machine{
Good list[];
public Machine(String name[]) {
this.list = new Good[name.length];
for(int i=0; i<name.length; i++) {
if(i%2==0) {
this.list[i]=new Good( false, name[i]);
}
else {
this.list[i]=new Good( true, name[i]);
}
}
}
public void checkBag(String name)throws DangerException{
boolean k=false;
for(int i=0; i<list.length; i++)
{
if(list[i].name.equals(name)) {
k=true;
if(list[i].isDanger)
throw new DangerException();
else System.out.println(name+"不是危险品");
}
}
if(k==false) System.out.println("未定义类别");
}
}
public class test_main {
public static void main(String[] args) {
// TODO 自动生成的方法存根
String name[]= {"苹果","炸药","西服","硫酸","手表","硫磺"};
Machine machine = new Machine(name);
for(int i=0; i<name.length; i++) {
try {
machine.checkBag(name[i]);
}
catch(DangerException e){
System.out.print(name[i]);
e.toShow();
}
}
try {
machine.checkBag("asdf");
}
catch(DangerException e){
System.out.print("asdf");
e.toShow();
}
}
}
posted on 2017-11-26 14:35 MACHINE_001 阅读(382) 评论(0) 编辑 收藏 举报