JAVAProgrammer
2017-03-22 15:09:07浏览 3196
MainBook
public class MainBook {
static String[] datas = { "JavaSE", "JavaEE", "Mysql", "JavaScript",
"Html5" };
static int status;
public static void main(String[] args) {
do {
try {
show();
} catch (BookException e) {
System.out.println(e.getMessage());
} catch (InputMismatchException e) {
System.out.println("输入类型不正确");
} catch (Exception e) {
System.out.println("未知异常");
}
} while (status == 0);
}
public static void show() throws BookException {
status = 0;
boolean flag = true;
do {
System.out.println("输入命令:1.按照名称查找书籍2.按照序号查找书籍(序号从0开始)0.退出程序");
Scanner sc = new Scanner(System.in);
int result = sc.nextInt();
if (result == 0) {
System.out.println("你已退出本程序,欢迎下次使用");
status = 1;
flag = false;
} else if (result == 1) {
System.out.print("请输入书籍名称: ");
String bookName = sc.next();
getByName(bookName);
} else if (result == 2) {
System.out.print("请输入书籍名称: ");
int bookNumber = sc.nextInt();
getByNumber(bookNumber);
} else {
throw new BookException("命令错误");
}
} while (flag);
}
public static void getByName(String bookName) throws BookException {
for (String bName : datas) {
if (bName.equals(bookName)) {
System.out.println("book: " + bName);
return;
}
}
throw new BookException("图书不存在");
}
public static void getByNumber(int bookNumber) throws BookException {
for (int i = 0; i < datas.length; i++) {
if (bookNumber == i) {
System.out.println("book: " + datas[i]);
return;
}
}
throw new BookException("图书不存在");
}
}
BookException
public class extends Exception {
public BookException() {
}
public BookException(String message) {
super(message);
}
}
效果图
热门评论
你好,我想问一下这个staus是用来干嘛的?
我想问下getByNumber方法为什么要用for循环,直接输出datas[bookNumber-1]不可以么
为什么用到static修饰词?,能否不用也是一样的?