Also create a ControllerCreate class that extends Controller.The create method takes as arguments the name of a new library user, a number of books (as a string), and an integer representing the role of user to create (where the integer 0 means a lender and the integer 1 means a borrower). The create method of the controller then transforms the book number from a string to an integer (using the Integer.parseInt static method), creates an object from the correct class (based on the role specified by the user input: lender or borrower) and calls the addUser method of the library to add the new user object to the library. • If no exception occurs then the create method of the controller returns the empty string. • If the constructor of the Borrower class throws a NotALenderException then the create method of the controller must catch this exception and return as result the error message from the exception object. • If the parseInt method of the Integer class throws a NumberFormatException (because the user typed something which is not an integer) then the create method of the controller must catch this exception and return as result the error message from the exception object. 写出符合以上要求的java代码
时间: 2023-12-06 18:39:39 浏览: 25
Here is the code for the ControllerCreate class:
```
public class ControllerCreate extends Controller {
public String create(String name, String bookCount, int role) {
try {
int books = Integer.parseInt(bookCount);
User user;
if (role == 0) {
user = new Lender(name, books);
} else {
user = new Borrower(name, books);
}
library.addUser(user);
} catch (NumberFormatException e) {
return e.getMessage();
} catch (NotALenderException e) {
return e.getMessage();
}
return "";
}
}
```
In this code, we create a new class called `ControllerCreate` that extends the `Controller` class. The `create` method takes three arguments: the name of the new user, the number of books as a string, and an integer representing the role of the user to create.
First, we use `Integer.parseInt` to convert the `bookCount` string into an integer. If this throws a `NumberFormatException`, we catch it and return the error message.
Next, we check the `role` integer to determine whether to create a `Lender` or `Borrower` object. We then call the `addUser` method of the library to add the new user to the library.
If the `Borrower` constructor throws a `NotALenderException`, we catch it and return the error message.
Finally, if no exception occurs, we return an empty string.