【交作業(yè)啦】
//自定義異常1:命令錯誤異常
package com.imooc.exceptionTest;
public class wrongCommandException extends Exception {
????? public wrongCommandException() {
?? }
????? public wrongCommandException(String message) {
????? super(message);
?? }
}
//自定義異常2:圖書不存在異常
package com.imooc.exceptionTest;
public class wrongNameException extends Exception {
????? public wrongNameException() {
?? }
????? public wrongNameException(String message) {
????? super(message);
?? }
}
//測試類
package com.imooc.exceptionTest;
import java.util.Arrays;
import java.util.Scanner;
?
public class BorrowE {
?? public static void main(String[] args) {
????? BorrowE borrow = new BorrowE();
????? borrow.select();
?? }
?? public void select() {
????? String[] books = new String[] {"數(shù)據(jù)結構","Java從入門到精通","計算機網(wǎng)絡","操作系統(tǒng)","數(shù)字圖像處理"};
????? System.out.println("輸入命令:1-按照名稱查找圖書; 2-按照序號查找圖書");
????? Scanner input = new Scanner(System.in);
????? try{
??????? if(input.hasNextInt()) {
?????????? int in = input.nextInt();
?????????? if(in==1) {
????????????? System.out.println("輸入圖書名稱:");
????????????? Scanner input2 = new Scanner(System.in);
????????????? String inM = input2.nextLine();
????????????? boolean flag = Arrays.asList(books).contains(inM);
????????????? if(flag) {
???????????????? System.out.println(inM+"存在!");
????????????? }else {
???????????????? throw new wrongNameException();
????????????? }
?????????? }else if(in==2) {
????????????? System.out.println("輸入圖書序號:");
????????????? int inN = input.nextInt();
????????????? if(inN>=0 && inN<books.length) {
???????????????? System.out.println("你要查詢的圖書名稱為:"+books[inN]);
????????????? }else {
????????????? ?? throw new wrongNameException();
????????????? }
?????????? }else {
????????????? throw new wrongCommandException();
?????????? }
??????? }else {
?????????? throw new wrongCommandException();
??????? }
????? }catch(wrongCommandException e){
??????? System.out.println("命令錯誤!請根據(jù)提示輸入數(shù)字命令!");
??????? select();
????? }catch(wrongNameException e) {
??????? System.out.println("圖書不存在!");
??????? select();
????? }
?? }
}
2019-03-18
有點問題,第二個輸序號的地方之前也需要if(input.hasNextInt()) 判斷是否為整數(shù)輸入
2019-03-18
琢磨半天視頻不如看這一篇作業(yè),多謝
2019-02-27
寫得很清晰,看完基本就明白了思路,謝謝!