package com.exception;
import java.util.*;
public class Test {
String[] book = {"高数","英语","语文","数据","java"};
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
int receive = scanner.nextInt();
Test test = new Test();
try {
switch(receive) {
case 1:
test.book();
break;
case 2:
test.num();
break;
default:
throw new NoBookException("命令输入错误!请根据提示输入数子命令!");
}
}catch(NoBookException e) {
e.printStackTrace();
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
}
}
public void book() throws NoBookException{
System.out.println("输入图书名称:");
Scanner sb = new Scanner(System.in);
String name = sb.next();
boolean flag = false;
for(String bk:book) {
if(name.equals(bk)) {
flag = true;
break;
}
}
if(flag) {
System.out.println("book:"+name);
}else {
throw new NoBookException("图书不存在!");
}
}
public void num() throws NoBookException{
System.out.println("输入图书序号:");
Scanner sn = new Scanner(System.in);
int i = sn.nextInt();
String str = book[i-1];
if(str == null || str.equals("")) {
throw new NoBookException("图书不存在!");
}else {
System.out.println("book:"+str);
}
}
}
没有异常提示语句啊
为什么,你在try{}用到book()方法,而这个方法后面才定义,在main方法中,是从上到下执行的,虽然你有用try铺抓异常,但最好还是先定义后使用;
NoBookException??这个是你自己定义的异常吗?