//命令错误异常
package imooc;
public class ErroCommandExp extends Exception {
public ErroCommandExp(){
}
public ErroCommandExp(String message){
super(message);
}
}
//图书不存在异常
package imooc;
import java.util.InputMismatchException;
public class NonBookExp extends InputMismatchException {
public NonBookExp(){
}
public NonBookExp(String message){
super(message);
}
}
//主函数
package imooc;
import java.util.InputMismatchException;
//import java.util.NoSuchElementException;
import java.util.Scanner;;
public class Initial {
public int command() throws ErroCommandExp{
Scanner input = new Scanner(System.in);
int i;
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
try{
i = input.nextInt(); //输入不匹配异常
}catch(InputMismatchException e){
throw new ErroCommandExp("命令错误异常");
}
if( (i != 1) && (i != 2) ){ //输入命令非1、2异常
throw new ErroCommandExp("命令错误异常");
}
return i;
}
public void searchName(String[] bookStore) throws NonBookExp{
Scanner input = new Scanner(System.in);
int k = 0;
System.out.println("请输入图书名称:");
String bookName = input.nextLine();
for( ;k < bookStore.length; k++){ //输入的图书名称一个个做对比
if(bookStore[k].equals(bookName)){
System.out.println("book:" + bookName);
break; //如果找到则输出图书的名称并 跳出for循环
}
}
if(k == bookStore.length){ //对比完仍没找到这抛出图书不存在异常
throw new NonBookExp("图书不存在异常");
}
}
public void searchId(String[] bookStore) throws NonBookExp{
Scanner input = new Scanner(System.in);
System.out.println("请输入图书序号:");
int bookNum = input.nextInt();
if( (bookNum >= bookStore.length) || (bookNum < 0) ){ //输入图书的编号小于零或者大于图书的数量则抛出图书不存在异常
throw new NonBookExp("图书不存在异常");
}else{
System.out.println("book:" + bookStore[bookNum]);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] bookStore = {"数据结构", "高数", "Java核心技术卷一", "Java核心技术卷二"};
Initial book = new Initial();
while(true){
int n = 0;
try{
n = book.command();
}catch(ErroCommandExp e){
System.out.println("命令错误,请从新输入!!!");
}
switch(n){
case 1: try{
book.searchName(bookStore);
}catch(NonBookExp e){
System.out.println("图书不存在!!!");
}
break;
case 2: try{
book.searchId(bookStore);
}catch(NonBookExp e){
System.out.println("图书不存在!!!");
}
break;
}
}
}
}
点击查看更多内容
5人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦