實現代碼如下
復制粘貼格式化,我還沒調試,如果有錯誤可以回復分享一下。
package com.booksearch;
import java.util.*;
public class BookSearch {
public static void main(String[] args) {
String[] books = { "數據結構", "高數", "論語" };
boolean flag = true;
while (flag) {
try {
System.out.println("輸入命令:1.按照名稱查圖書;2.按照序號查圖書");
Scanner input = new Scanner(System.in);
int cmdnum = input.nextInt();
if (cmdnum == 1) {
System.out.println("輸入圖書名稱:");
String name = input.next();
for (String book : books) {
if (book.equals(name)) {
System.out.println("book:" + book);
flag = false;
break;
}
}
if (flag) {
System.out.println("圖書不存在");
continue;
}
} else if (cmdnum == 2) {
System.out.println("輸入圖書序號:");
int id = input.nextInt();
for (int i = 0; i < books.length; i++) {
if (id > 0 && id <= books.length) {
System.out.println("book:" + books[id - 1]);
flag = false;
break;
}
}
if (flag) {
System.out.println("圖書不存在");
continue;
}
}
} catch (Exception e) {
System.out.println("命令輸入錯誤!請輸入數字命令!");
continue;
}
}
}
}
2018-08-12
try catch沒用吧。。