骑猪跑的程序员
2017-07-31 16:41:02浏览 2486
import java.util.Scanner;
public class SimulateLibrary {
public String[][] Books = {{"1","十万个为什么"},{"2","Java语言程序设计"},{"3","JavaScript权威指南"},{"4","网页设计"}};
public static void main(String[] args) {
System.out.println("请输入你要搜索的方式:");
System.out.println("1. 按照图书序号搜索");
System.out.println("2. 按照书名搜索");
SimulateLibrary SL = new SimulateLibrary();
Scanner sc = new Scanner(System.in);
int index = sc.nextInt();
if(index == 1) {
System.out.println("请输入图书序号");
int BookIndex = sc.nextInt();
SL.SearchByIndex(BookIndex);
}else if(index == 2) {
System.out.println("请输入图书全名");
String BookName = sc.next();
SL.SearchByBookName(BookName);
}else {
System.out.println("命令输入有误,请根据提示输入数字命令!");
}
sc.close();
}
public void SearchByIndex(int BookIndex) {
BookIndex--;
try {
System.out.println("找到书本《"+Books[BookIndex][1]+"》");
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("图书不存在");
}catch(Exception e) {
System.out.println("错误命令异常,请重新输入");
}
}
public void SearchByBookName(String BookName) {
String findBook = null;
int BookNum = -1;
for(int i=0;i<Books.length;i++) {
if(Books[i][1].equals(BookName)) {
findBook = Books[i][1];
BookNum = i+1;
break;
}
}
if(BookNum!=-1) {
System.out.println("找到书本《"+findBook+"》,图书序号"+BookNum);
}else {
System.out.println("图书不存在");
}
}
}
热门评论
二维数组,思维很强,很厉害的方法