The moreBook method takes as argument the name of a user and a number of books and changes the number of books currently borrowed by that user. If the library does not have a user with the given name, then the moreBook method must throw an UnknownUserException with the message "User XXX unknown.", where XXX is replaced with the name of the user. Do not worry about multiple users having the same name. Note: the moreBook method does not catch any exception, it only throws exceptions. Hint: use the equals method to compare strings, not the == operator which only works with constant strings.
时间: 2023-11-27 10:51:59 浏览: 31
Here's an example implementation of the moreBook method in Java:
```
public void moreBook(String userName, int numBooks) throws UnknownUserException {
boolean foundUser = false;
for (User user : users) {
if (user.getName().equals(userName)) {
user.setNumBooks(user.getNumBooks() + numBooks);
foundUser = true;
break;
}
}
if (!foundUser) {
throw new UnknownUserException("User " + userName + " unknown.");
}
}
```
Assuming that you have a list of User objects called `users`, this method loops through all users and checks if the name of the current user matches the given `userName`. If a match is found, the `numBooks` property of the user is increased by `numBooks`. If no user is found with the given name, an UnknownUserException is thrown with the appropriate message.
Note that we use the `equals` method to compare strings, not the `==` operator, which only works with constant strings.