實(shí)現(xiàn)代碼如下
復(fù)制粘貼格式化,我還沒調(diào)試,如果有錯(cuò)誤可以回復(fù)分享一下。
package com.booksearch;
import java.util.*;
public class BookSearch {
public static void main(String[] args) {
String[] books = { "數(shù)據(jù)結(jié)構(gòu)", "高數(shù)", "論語" };
boolean flag = true;
while (flag) {
try {
System.out.println("輸入命令:1.按照名稱查圖書;2.按照序號(hào)查圖書");
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("輸入圖書序號(hào):");
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("命令輸入錯(cuò)誤!請(qǐng)輸入數(shù)字命令!");
continue;
}
}
}
}
2018-08-12
try catch沒用吧。。