2013-07-27 2 views
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, t 그는 오류가 잡히고 "INVALID BOOK INDEX!"라는 문구가 인쇄됩니다.

그러나 책 색인의 문자 또는 문자열을 입력하면 "INVALID LIBRARY ACTION!" "INVALID INPUT!"이 인쇄되어야 할 때.

기본 절이 catch를 무시하는 것으로 보입니까?

답변

1

변수는 항상 String입니다. Scanner.nextLine()String을 반환하므로 항상 변수가 있습니다.

따라서 default 문이 실행되고 InputMismatchException 캐치가 실행되지 않는다고 가정하는 것이 합리적입니다.

입력 승인을 세부적으로 조정하려면 Scanner "다음"방법도 참조하십시오.

예 :

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 
} 
+0

안녕하세요 Mena, 코드를 친절하게 고쳐 주시겠습니까? 그것이 내가 지금 놓치고있는 유일한 것입니다. 고맙습니다. –

+0

@ user2539182 전체 코드를 수정하지는 않겠지 만 답변에 스 니펫을 추가 할 수 있습니다. 곧 수정을 참조하십시오. – Mena

+0

무한 루프가 바뀌 었습니다. 감사. "반복 할당"이란 정확히 무엇을 의미합니까? –

0

은 try-캐치 내가보다 INT 큰 입력 할 때 캐치 문 중 하나 OutOfBounds 또는 InputMismatch 오류가 발생합니다 제거 String sAction에 대한 int book_chosen하지을 위해이기 때문에 3 (OutOfBounds) 또는 int book_chosen (Enter book index:)의 char/string (InputMismatch).

두 catch 문이 모두 있지만 해당 메시지를 표시하지 않으면 오류를 catch하는 것을 관찰했습니다. 모두가 "무효"입력 어쨌든이기 때문에, 그냥 모든 오류가 프롬프트를 변경하여 주위에 내 길을 발견

Library 클래스 INVALID INPUT!에 :

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!"); 
    } 
} 
}