编写一异常处理程序,模拟地铁、机场进行危险品与违禁物品检查。程序循环接受输入字符串,检查字符串。若其中含有’b’‘o’‘m’‘b’四个字母(字母顺序无关)就抛出发现危险品异常,提示有危险品炸弹;若其中含有’h’’e’’r’’o’’i’’n’六个字母则抛出发现违禁品异常。如果没有异常,程序循环接受输入字符串。
题目分析,可以知道有两类异常,则需要两个异常类,一个检测方法包含这两个类的异常抛出,和一个总的测试类就可。
这里我采用的检测方法是通过String类的indexof方法来查看是否包含。
两个异常类
public class bombException extends Exception{//检查危险品异常类
String message;
public bombException(String s){
message=s+"危险品异常!";
}
public String toString(){
return message;
}
}
public class heroinException extends Exception{//检查违禁品异常类
String message;
public heroinException(String s){
message=s+"违禁品异常!";
}
public String toString(){
return message;
}
}
一个检测方法
public class Check{//检查类
public static void checkBomb(String s) throws bombException{//检查危险品
String []str={"b","o","m","b"};
int tag=1;
for(int i=0;i<str.length-1;i++){//比较s字符串中是否含有b、o、m、字符
if(s.indexOf(str[i])==-1){//不含有则返回beak,不抛出异常
tag=-1;
break;
}
}
if(tag==1){//如果tag=1,则含有,抛出异常
throw new bombException(s);
}
}
public static void checkHeroin(String s) throws heroinException{//检查违禁品
String []str={"h","e","r","o","i","n"};
int tag=1;
for(int i=0;i<str.length-1;i++){//比较s字符串中是否含有h\e\r\o\i\n字符
if(s.indexOf(str[i])==-1){//不含有则tag=-1,返回break,不抛出异常
tag=-1;
break;
}
}
if(tag==1){//如果tag=1,则说明含有,则抛出异常
throw new heroinException(s);
}
}
}
这里是不在意字母顺序的检测,如果题目要求字母的顺序,则修改检测方法如下:
public class Check1{//检查类
public static void checkBomb(String s) throws bombException{//检查危险品
String []str={"b","o","m","b"};
int tag=1;
int loc=0;
for(int i=0;i<str.length-1;i++){//比较s字符串中是否含有h\e\r\o\i\n字符
if(s.indexOf(str[i],loc)==-1){//不含有则tag=-1,返回break,不抛出异常
tag=-1;
break;
}else{//含有则从含有的地方往后查找是否含有余下的字符 :加上loc则是和字母的顺序相关的,如果不用loc,直接indefOf(str[i]),则和字母顺序无关
loc=s.indexOf(str[i],loc);
}
}
if(tag==1){//如果tag=1,则含有,抛出异常
throw new bombException(s);
}
}
public static void checkHeroin(String s) throws heroinException{//检查违禁品
String []str={"h","e","r","o","i","n"};
int tag=1;
int loc=0;
for(int i=0;i<str.length-1;i++){//比较s字符串中是否含有h\e\r\o\i\n字符
if(s.indexOf(str[i],loc)==-1){//不含有则tag=-1,返回break,不抛出异常
tag=-1;
break;
}else{
loc=s.indexOf(str[i],loc);//含有则从含有的地方往后查找是否含有余下的字符
}
}
if(tag==1){//如果tag=1,则说明含有,则抛出异常
throw new heroinException(s);
}
}
}
通常来说,字母顺序是要的,而且不规定字母顺序的话,对于重复的字母,通过indexof无法保证含有多个重复字母。
最后是主类
import java.util.Scanner;
public class Example_05{
public static void main(String args[]){
Scanner reader = new Scanner(System.in);
String s;//记录物品
System.out.println("请输入物品的名称:(EOF结束)");
do{//检测
s=reader.nextLine();
try{//检测异常
Check1.checkBomb(s);//检测危险品异常
Check1.checkHeroin(s);//检测违禁品异常
}
catch(bombException e){//接受到危险品异常
System.out.println(e.toString());//输出危险信息
}
catch(heroinException e){//接受到违禁品异常
System.out.println(e.toString());//输出违禁信息
}
}while(s.equals("EOF")!=true);
}
}