When the user of the system specifies action 3, your program must ask the user to type the name of a user, and the program then prints the number of books which is currently borrowed by this user. If the name of the user is wrong, then an UnknownUserException exception will be thrown by the Library object. The code of the main method of your CLI class must catch this exception, print the error message from the exception object, and then it just goes back to printing the menu of actions (by just going back to the beginning of the while loop).
时间: 2023-11-22 07:55:22 浏览: 102
Average-is-not-Fast-Enough.rar_The First_distance relay
Here's an example implementation of the main method that fulfills the requirement you described:
```java
import java.util.Scanner;
public class CLI {
public static void main(String[] args) {
Library library = new Library();
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Choose an action:");
System.out.println("1. Print all books");
System.out.println("2. Borrow a book");
System.out.println("3. Check number of books borrowed by a user");
int choice = scanner.nextInt();
scanner.nextLine(); // consume the newline character
switch (choice) {
case 1:
library.printAllBooks();
break;
case 2:
System.out.println("Enter the name of the book to borrow:");
String bookName = scanner.nextLine();
System.out.println("Enter your name:");
String userName = scanner.nextLine();
try {
library.borrowBook(bookName, userName);
System.out.println("Book successfully borrowed!");
} catch (BookNotAvailableException e) {
System.out.println("Sorry, that book is not available.");
} catch (UnknownUserException e) {
System.out.println("Sorry, we don't recognize that user.");
}
break;
case 3:
System.out.println("Enter the name of the user:");
String checkUserName = scanner.nextLine();
try {
int numBorrowed = library.getNumBooksBorrowed(checkUserName);
System.out.println(checkUserName + " has borrowed " + numBorrowed + " books.");
} catch (UnknownUserException e) {
System.out.println("Sorry, we don't recognize that user.");
}
break;
default:
System.out.println("Invalid choice.");
}
}
}
}
```
Note how we catch the `UnknownUserException` when calling `library.getNumBooksBorrowed()`, print the error message using `e.getMessage()`, and then just continue the loop to print the menu of actions again.
阅读全文