JAVA异常练习——编程例题之检查危险品

//goods.java
public class goods{
//boolean IsDanger;
String name;
/*
public void setIsDanger(boolean IsDanger){
this.IsDanger=IsDanger;
}
public boolean getIsDanger(){
return IsDanger;
}
*/
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}

//dangerException.java
public class dangerException extends Exception{
String message;
dangerException(String message){
this.message=message;
}
void showMessage(){
System.out.println(message);
}
}

//machine.java
public class machine{
String name;
goods g;
machine(goods g){
this.g=g;
name=g.getName();
try{
//if(name=="炸弹")会出错 区分String类如何判断字符串相等的两种情况 
if(name.equals("炸弹")||name.equals("毒药")||name.equals("刀具")||name.equals("毒 药")){
System.out.println(name);
throw new dangerException("注意危险!发现危险品!!!");
}
else{
throw new dangerException("检查通过!未发现危险品!");
}
}
catch(dangerException e){
e.showMessage();
}
}

}
//checkMain.java
import java.util.Scanner;

public class checkMain{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
OUTER:while(true){
//String input=sc.next();注意next()和nextLine()区别
//例 输入abc def ghi 
//next()读取abc      nextLine()读取abc def ghi一整行
String input=sc.nextLine();
goods g=new goods();
g.setName(input);
machine m=new machine(g);
if(input.equals("退出")||input.equals("结束")){
break OUTER;
}

}
}
}

输出:

JAVA异常练习——编程例题之检查危险品_第1张图片

参考自 《java面向对象程序设计——实验指导与习题解答(张跃平等 著)》

你可能感兴趣的:(JAVA学习)