請問各位大佬,為什么當我異常輸入指令時,比方說輸入查找指令為a時,我想要輸出的(第一句話:命令輸入錯誤,請根據提示輸入命令),就是不輸出呢? throw new libraryException("第一句話:命令輸入錯誤,請根據提示輸入命令")這行代碼到底有什么作用呢?
package $$$$$$$;
public class libraryException extends Exception{//自定義異常
public libraryException() {//無參方法
}
public libraryException(String message) {//有參構造方法
super(message);
}}
package $$$$$$$;
import java.util.Scanner;
public class library {
?public static void main(String[] args) {//入口
? Index();
?}
?public static void?Index()?{
? System.out.println("歡迎進入圖書館查書系統(tǒng)\n請輸入您的指令:\n1-按名稱查找圖書\n2-按編號查找圖書\n");
? Scanner in = new Scanner(System.in);
? String i = in.next();
? try {
? ?if (i.equals( "1")) {
? ? System.out.println("請輸入您需要查找的圖書的書名");
? ? name();
? ?} else if (i.equals( "2")) {
? ? System.out.println("請輸入您需要查找的圖書的編號");
? ? number();
? ?} else {
System.out.println("測試");
? ? throw new?libraryException("第一句話:命令輸入錯誤,請根據提示輸入命令");
? ?}
? } catch (Exception e) {
? ?System.out.println("第二句話:請輸入正確指令\n");
? ?Index();
? }
?}
}
請問各位大佬,為什么當我異常輸入指令時,比方說輸入查找指令為a時,我想要輸出的(第一句話:命令輸入錯誤,請根據提示輸入命令),就是不輸出呢?
throw new libraryException("第一句話:命令輸入錯誤,請根據提示輸入命令")這行代碼到底有什么作用呢?
謝謝大佬幫忙解答
下面是運行結果
2019-03-04
就看你的main吧,主要問題在這里(上面的框),在拋出libraryException的時候程序不會輸出“第一句話:命令輸入錯誤……”按照拋出異常的順序而是應該在后面的catch中輸出語句,所以這塊的代碼應該改成后面我寫的那個(下面的框),然后你再試試。
2019-03-04
public static void name() {//name方法
? Scanner in = new Scanner(System.in);
? String str = in.nextLine();
? int index = -1;
? try {
? ?for (int i = 0; i < BOOK.length; i++) {
? ? if (BOOK[i][1].equals(str)) {
? ? ?index = i;
? ? ?break;
? ? }
? ?}
? ?if (index != -1) {
? ? System.out.println("編號: " + BOOK[index][0] + "? 書名 " + BOOK[index][1] + " 存在");
? ?} else {
? ? throw new Exception();
? ?}
? } catch (Exception e) {
? ?System.out.println("該書不存在,請重新輸入正確書名......");
? ?name();
? }
?}
public static void number() {//number方法
? Scanner in = new Scanner(System.in);
? String str = in.nextLine();
? int index = -1;
? try {
? ?for (int i = 0; i < BOOK.length; i++) {
? ? if (BOOK[i][0].equals(str)) {
? ? ?index = i;
? ? ?break;
? ? }
? ?}
? ?if (index != -1) {
? ? System.out.println("編號: " + BOOK[index][0] + "? 書名 " + BOOK[index][1] + " 存在");
? ?} else {
? ? throw new Exception();
? ?}
? } catch (Exception e) {
? ?System.out.println("該書不存在,請重新輸入正確編號......");
? ?number();
? }
?}
?
?public static String[][] BOOK = {{"0001","語文"},{"0002","數學"},{"0003","英語"},{"0004","體育"}};
}
2019-03-04
能把number();的代碼貼上來看看嗎