0

包装 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!”

默认子句似乎覆盖了捕获?

4

2 回答 2

1

您的sAction变量始终是 a String,因为Scanner.nextLine()返回String

因此,您的default语句被触发,并且假设InputMismatchExceptioncatch 永远不会执行是合理的。

如果您想微调您的输入接受度,另请参阅其他扫描仪“下一步”方法。

例子:

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 
}
于 2013-07-27T13:07:57.163 回答
0

由于 try-catch 是针对int book_chosen不是针对的String sAction,因此当我为 ( ) 输入大于 3 的 int (OutOfBounds) 或字符/字符串 (InputMismatch) 时,删除任何 catch 语句都会引发 OutOfBounds 或 InputMismatchint book_chosen错误Enter book index:

我观察到当两个 catch 语句都存在时它正在捕获错误,但没有显示适当的消息。由于无论如何都是“无效”输入,我找到了解决方法,只需将所有错误提示更改为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!");
    }
}
}
于 2013-07-28T10:57:34.350 回答