簡體   English   中英

Java:切換默認的優先try-catch

[英]Java: Switch default overriding try-catch

打包 mylib

Library 課:

package mylib;

import java.util.*;

class Library {
public static void main(String[] args) {
    boolean isInfinite = true;
    int book_index;
    Scanner input = new Scanner(System.in);

    Book[] myBooks = new Book[3]; // Create an array of books

    // Initialize each element of the array
    myBooks[0] = new Book("The Lover's Dictionary", "Levithan, D.", 211);
    myBooks[1] = new Book("White Tiger", "Adiga, A.", 304);
    myBooks[2] = new Book("Thirteen R3asons Why", "Asher, J.", 336);

    do {
        // Print book listing
        System.out.println("\n***** BOOK LISTING *****");
            for(int i = 0; i < myBooks.length; i++) {
                Book book = myBooks[i];
                System.out.println("[" + (i + 1) + "] " + book.sTitle + "\nAuthor: " +
                    book.sAuthor + "\nPages: " + book.iPages + "\nStatus: " + book.sStatus);
                System.out.print("\r\n");
            }

        // Select library action
        System.out.println("***** SELECT ACTION *****");
        System.out.println("B - Borrow a book" + "\nR - Reserve a book" +
            "\nI - Return a book" + "\nX - Exit program");
        System.out.print("\nEnter command: ");
        String sAction = input.nextLine();

        try {
            switch(sAction.toUpperCase()) { // Converts input to uppercase
                // Borrow a book
                case "B":
                    System.out.println("\n***** BORROW A BOOK *****");

                    System.out.print("Enter book index: ");
                    book_index = input.nextInt();
                    input.nextLine();

                    myBooks[book_index-1].borrowBook(); // Call method from another class
                break;

                // Reserve a book
                case "R":
                    System.out.println("\n***** RESERVE A BOOK *****");

                    System.out.print("Enter book index: ");
                    book_index = input.nextInt();
                    input.nextLine();

                    myBooks[book_index-1].reserveBook(); // Call method from another class
                break;

                // Return a book
                case "I":
                    System.out.println("\n***** RETURN A BOOK *****");

                    System.out.print("Enter book index: ");
                    book_index = input.nextInt();
                    input.nextLine();

                    myBooks[book_index-1].returnBook(); // Call method from another class
                break;

                // Exit the program
                case "X":
                    System.out.println("\nTerminating program...");
                    System.exit(0);
                break;

                default:
                    System.out.println("\nINVALID LIBRARY ACTION!");
                break;
            }
        }
        catch(ArrayIndexOutOfBoundsException err) {
            System.out.println("\nINVALID BOOK INDEX!");
        }
        catch(InputMismatchException err) {
            System.out.println("\nINVALID INPUT!");
        }
    } while(isInfinite);
}
}

Book 類:

package mylib;

class Book {
int iPages;
String sTitle, sAuthor, sStatus;

public static final String AVAILABLE = "AVAILABLE",
    BORROWED = "BORROWED", RESERVED = "RESERVED";

// Constructor
public Book(String sTitle, String sAuthor, int iPages) {
    this.sTitle = sTitle;
    this.sAuthor = sAuthor;
    this.iPages = iPages;
    this.sStatus = Book.AVAILABLE; // Initializes book status to AVAILABLE
}
// Constructor accepts no arguments
public Book() {
}

// Borrow book method
void borrowBook() {
    if(sStatus.equals(Book.AVAILABLE) || sStatus.equals(Book.RESERVED)) {
        sStatus = Book.BORROWED;

        System.out.println("\nBORROW SUCCESSFUL!");
    }
    else {
        System.out.println("\nBOOK IS UNAVAILABLE!");
    }
}

// Reserve book method
void reserveBook() {
    if(sStatus.equals(Book.AVAILABLE)) {
        sStatus = Book.RESERVED;

        System.out.println("\nRESERVE SUCCESSFUL!");
    }
    else {
        System.out.println("\nBOOK IS UNAVAILABLE!");
    }
}

// Return book method
void returnBook() {
    if(sStatus.equals(Book.AVAILABLE)) {
        System.out.println("\nBOOK IS ALREADY AVAILABLE!");
    }
    else if(sStatus.equals(Book.RESERVED)) {
        System.out.println("\nBOOK IS ALREADY RESERVED!");
    }
    else {
        sStatus = Book.AVAILABLE;
    }
}
}

當我輸入無效的書索引時,例如說4,將捕獲錯誤並顯示“ INVALID BOOK INDEX!”。

但是,當我為書索引輸入一個字符或字符串時,它會顯示“ INVALID LIBRARY ACTION!”。 應該打印“ INVALID INPUT!”時

默認子句似乎覆蓋了捕獲?

您的sAction變量始終是String ,因為Scanner.nextLine()返回String

因此,將觸發您的default語句,並且可以合理地假設InputMismatchException捕獲將永遠不會執行。

如果您想微調輸入接受度,請參閱其他掃描儀 “下一個”方法。

例:

while (true) { // your infinite loop - better use a while-do instead of a do-while here
  String sAction = input.nextLine(); // we assign sAction iteratively until user "quits"
  // No try-catch: ArrayIndexOutOfBoundsException is unchecked and you shouldn't catch it.
  // If it bugs, fix the code. 
  // No InputMismatchException either, as you don't need it if you use nextLine

  // your switch same as before 
}

由於try-catch是針對int book_chosen 而非 String sAction ,因此當我輸入大於3的int(OutOfBounds)或char / string(InputMismatch)時,刪除任何catch語句都會拋出OutOfBounds或InputMismatch錯誤。 int book_chosenEnter book index: int book_chosen

我發現當兩個catch語句都存在時,它正在捕獲錯誤,但是沒有顯示適當的消息。 由於所有輸入都是“無效”輸入,因此通過將所有錯誤提示更改為INVALID INPUT! ,我找到了解決方法INVALID INPUT!

Library課:

package mylib;

import java.util.*;

class Library {
static int book_index;
static Scanner input = new Scanner(System.in);

static void getIndex() {
    System.out.print("Enter book index: ");
    book_index = input.nextInt();
    input.nextLine();
}

public static void main(String[] args) {
    // Create an array of books
    Book[] myBooks = new Book[3];

    // Initialize each element of the array
    myBooks[0] = new Book("The Lover's Dictionary", "Levithan, D.", 211);
    myBooks[1] = new Book("White Tiger", "Adiga, A.", 304);
    myBooks[2] = new Book("Thirteen R3asons Why", "Asher, J.", 336);

    while(true) {
        // Print book listing
        System.out.println("\n***** BOOK LISTING *****");
            for(int i = 0; i < myBooks.length; i++) {
                Book book = myBooks[i];
                System.out.println("[" + (i + 1) + "] " + book.sTitle +
                    "\nAuthor: " + book.sAuthor + "\nPages: " +
                    book.iPages + "\nStatus: " + book.sStatus);
                System.out.print("\r\n");
            }

        // Select library action
        System.out.println("***** SELECT ACTION *****");
        System.out.println("B - Borrow a book" + "\nR - Reserve a book" +
            "\nI - Return a book" + "\nX - Exit program");
        System.out.print("\nEnter command: ");
        String sAction = input.nextLine();

        try {
            switch(sAction.toUpperCase()) {
                // Borrow a book
                case "B":
                    System.out.println("\n***** BORROW A BOOK *****");
                    getIndex();
                    myBooks[book_index-1].borrowBook();
                break;

                // Reserve a book
                case "R":
                    System.out.println("\n***** RESERVE A BOOK *****");
                    getIndex();
                    myBooks[book_index-1].reserveBook();
                break;

                // Return a book
                case "I":
                    System.out.println("\n***** RETURN A BOOK *****");
                    getIndex();
                    myBooks[book_index-1].returnBook();
                break;

                // Exit the program
                case "X":
                    System.out.println("\nTerminating program...");
                    System.exit(0);
                break;

                default:
                    System.out.println("\nINVALID INPUT!");
                break;
            }
        }
        catch(ArrayIndexOutOfBoundsException err) {
            System.out.println("\nINVALID INPUT!");
        }
        catch(InputMismatchException err) {
            System.out.println("\nINVALID INPUT!");
        }
    }
}
}

Book類:

package mylib;

class Book {
int iPages;
String sTitle, sAuthor, sStatus;

public static final String AVAILABLE = "AVAILABLE",
    BORROWED = "BORROWED", RESERVED = "RESERVED";

// Constructor
public Book(String sTitle, String sAuthor, int iPages) {
    this.sTitle = sTitle;
    this.sAuthor = sAuthor;
    this.iPages = iPages;
    this.sStatus = Book.AVAILABLE;
}

// Constructor accepts no arguments
public Book() {
}

// Borrow book method
void borrowBook() {
    if(sStatus.equals(Book.AVAILABLE) || sStatus.equals(Book.RESERVED)) {
        sStatus = Book.BORROWED;
        System.out.println("\nBORROW SUCCESSFUL!");
    }
    else {
        System.out.println("\nBOOK IS UNAVAILABLE!");
    }
}

// Reserve book method
void reserveBook() {
    if(sStatus.equals(Book.AVAILABLE)) {
        sStatus = Book.RESERVED;
        System.out.println("\nRESERVE SUCCESSFUL!");
    }
    else {
        System.out.println("\nBOOK IS UNAVAILABLE!");
    }
}

// Return book method
void returnBook() {
    if(sStatus.equals(Book.AVAILABLE)) {
        System.out.println("\nBOOK IS AVAILABLE!");
    }
    else if(sStatus.equals(Book.RESERVED)) {
        System.out.println("\nBOOK IS RESERVED!");
    }
    else {
        sStatus = Book.AVAILABLE;
        System.out.println("\nRETURN SUCCESSFUL!");
    }
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM