package com.yh;
import java.util.InputMismatchException;
import java.util.Scanner;
public class BorrowingSystem {
String books[] = {"高等数学","数据结构","计算方法"};
public void borrow(){
Scanner scan = new Scanner(System.in);
try {
System.out.println("输入命令:1-按照名称查找;2-按照序号查找");
int num = scan.nextInt();
switch (num) {
case 1:
try {
System.out.println("输入图书名称:");
String bookName = scan.next();
//根据下标值判断是否存在该图书
int i = 0;//初始化下标值
for(i = 0; i < books.length; i++){
//如果存在该图书,则输出该图书,并跳出for循环
if(bookName.equals(books[i])){
System.out.println("book:" + books[i]);
break;
}
}
//下标值等于字符串数组长度,则说明未查到该图书,抛出下标越界异常,并在catch块中捕获该异常
if(i == books.length){
throw new ArrayIndexOutOfBoundsException();
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("图书不存在!");
borrow();
}
break;
case 2:
try {
System.out.println("输入图书序号:");
int seqNum = scan.nextInt();
System.out.println("book:"+books[seqNum]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("图书不存在!");
borrow();
}
}
} catch (InputMismatchException e) {
System.out.println("命令输入错误!请根据提示输入数字命令!");
borrow();
}
}
public static void main(String[] args) {
BorrowingSystem bs = new BorrowingSystem();
bs.borrow();
}
}
共同学习,写下你的评论
评论加载中...
作者其他优质文章