旧时光__
2016-10-08 10:26:35浏览 2591
import java.util.Scanner;
import java.util.ArrayList;
public class BooksLable {
static ArrayList<String> books = new ArrayList<String>();
static ArrayList<String> books2 = new ArrayList<String>();
public static void main(String[] args) {
// TODO Auto-generated method stub
boolean isOk = true;
booksStore();
while (isOk) {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
int choice = choose();
if (choice == 1) {
bookSelect();
} else if (choice == 2) {
numSelect();
}
}
}
// 进行图书的序号以及书名存档
public static void booksStore() {
// TODO Auto-generated method stub
books.add("\t1\t高等数学");
books.add("\t2\t数据库");
books.add("\t3\tC语言");
books.add("\t4\tJAVA");
books.add("\t5\t机械原理");
books.add("\t6\t机械设计");
books.add("\t7\t机械制图");
for (int i = 0; i < books.size(); i++) {
books2.add(books.get(i).split("\t")[2]);
}
}
// 根据序列号查找图书
private static void numSelect() {
// TODO Auto-generated method stub
int num = 0;
boolean isError = true;
do {
try {
System.out.println("输入图书序号:");
Scanner input = new Scanner(System.in);
num = input.nextInt();
isError = false;
} catch (Exception e) {
// e.printStackTrace();
// System.out.println(e.getMessage());
System.out.println("命令行输入错误!请根据提示输入数字命令!");
}
} while (isError);
if (books.size() < num) {
System.out.println("图书不存在!");
} else {
System.out.println("book:" + books2.get(num));
}
}
// 根据书名查找图书
private static void bookSelect() {
// TODO Auto-generated method stub
boolean isSelect = false;
String lable = null;
System.out.println("请输入图书名称:");
Scanner input = new Scanner(System.in);
lable = input.nextLine();
for (int i = 0; i < books2.size(); i++) {
if (lable.equals(books2.get(i))) {
System.out.println("book:" + lable);
isSelect = true;
break;
}
}
if (isSelect == false) {
System.out.println("图书不存在!");
}
}
// 选择命令
private static int choose() {
// TODO Auto-generated method stub
int num = 0;
int lable = 0;// 用来标记输入错误是由于输入不匹配,还是由于输入数字既不是1也不是2
boolean isError = true;
do {
try {
Scanner input = new Scanner(System.in);
num = input.nextInt();
} catch (Exception e) {
// e.printStackTrace();
// System.out.println(e.getMessage());
System.out.println("命令行输入错误!请根据提示输入数字命令!");
lable = 0;
}
if (num != 1 && num != 2 && lable != 0) {
System.out.println("命令行输入错误!请根据提示输入数字命令!");
} else {
isError = false;
}
} while (isError);
return num;
}
}
热门评论
未来中国最伟大的女程序猿
一只学渣路过,叹为观止
main函数中捕获numSelect()异常。不然在选择1按照数字检索时,输入的数字超过所存储数量时,会产生角标越界异常