天天看點

java圖書館借書問題_圖書館借書系統-Java異常的學習和處理

定義了三個類

ErrorCodeException.java

public class ErrorCodeException extends Exception {

public ErrorCodeException(){

}

public ErrorCodeException(String message){

super(message);

}

}

NoExitBookException.java

public class NoExitBookException extends Exception {

public NoExitBookException() {

}

public NoExitBookException(String message) {

super(message);

}

}

BorrowBookSystem.java

public class BorrowBookSystem {

String[] library = {"Java", "Python", "javascript", "Android", "iOS", "Linux", "Unix", "C", "C++", "C#", "Ruby", "Django", "Flask"};

public static void main(String[] args) {

BorrowBookSystem system = new BorrowBookSystem();

system.borrow();

}

public void borrow() {

while (true) {

int command = 0;

try {

command = command();

} catch (ErrorCodeException e) {

System.out.println(e.getMessage());

}

if (command == 1) {

try {

queryBookName();

} catch (NoExitBookException e) {

System.out.println(e.getMessage());

}

} else if (command == 2) {

try {

queryBookCode();

} catch (ErrorCodeException e) {

System.out.println(e.getMessage());

} catch (NoExitBookException e) {

System.out.println(e.getMessage());

}

}

}

}

public int command() throws ErrorCodeException {

int result;

System.out.println("輸入查詢指令:1-按照圖書名稱查詢,2-按照圖書序列号查詢。");

Scanner scanner = new Scanner(System.in);

String command = scanner.next().trim();

if (command.equals("1")) {

result = 1;

} else if (command.equals("2")) {

result = 2;

} else {

throw new ErrorCodeException("指令輸入錯誤!請根據提示輸入數字指令!");

}

return result;

}

private void queryBookCode() throws ErrorCodeException, NoExitBookException {

System.out.println("輸入圖書序列号:");

Scanner scanner = new Scanner(System.in);

String next = scanner.next().trim();

int number;

try {

number = Integer.parseInt(next);

} catch (Exception e) {

throw new ErrorCodeException("指令輸入錯誤!請根據提示輸入數字指令!");

}

try {

String bookName = library[number];

System.out.println("book:" + bookName);

} catch (Exception e) {

throw new ErrorCodeException("圖書不存在!");

}

}

private void queryBookName() throws NoExitBookException {

System.out.println("輸入圖書名稱:");

Scanner scanner = new Scanner(System.in);

String next = scanner.next().trim();

boolean result = false;

for (int i = 0; i < library.length; i++) {

if (library[i].equals(next)) {

System.out.println("book:" + library[i]);

result = true;

break;

}

}

if (!result) {

throw new NoExitBookException("圖書不存在!");

}

}

}