However, a borrower cannot lend books, so the number of books borrowed by the borrower must always be positive or zero, never negative. If the argument given to the moreBook method is too negative and would change the book variable into a negative value, then the number of books borrowed by the borrower must not change and the moreBook method must throw a NotALenderException with the message “A borrower cannot lend XXX book(s).”, where XXX is replaced with the result of -(book + number).java代码

时间: 2024-01-21 19:01:51 浏览: 116
根据您提供的问题,我猜测您想问的是,如何在Java中实现根据条件抛出NotALenderException异常。您可以使用以下代码实现: ```java public void moreBook(int number) throws NotALenderException { if (book + number < 0) { throw new NotALenderException("A borrower cannot lend " + (-(book + number)) + " book(s)."); } book += number; } ``` 在代码中,如果借阅者所借图书的数量将导致图书变量成为负数,则会抛出NotALenderException异常,并显示消息“A borrower cannot lend XXX book(s).”,其中XXX是计算得出的值。否则,将更改book变量的值。注意,方法声明中使用了throws关键字,以指示该方法可能抛出NotALenderException异常。
相关问题

Add a class Borrower that extends User. The constructor of the Borrower class takes a name and a number of books borrowed by the borrower. If the number of books given as argument is strictly less than zero, then the constructor must throw a NotALenderException with the message "A new borrower cannot lend books.". The borrower class does not have any instance variable.java代码

Sure, here's your Java code: ```java public class Borrower extends User { public Borrower(String name, int numBooksBorrowed) throws NotALenderException { super(name); if(numBooksBorrowed < 0) { throw new NotALenderException("A new borrower cannot lend books."); } } } ``` Here, we have defined a `Borrower` class that extends the `User` class. The constructor of the `Borrower` class takes a name and a number of books borrowed by the borrower. If the number of books given as argument is strictly less than zero, then the constructor throws a `NotALenderException` with the message "A new borrower cannot lend books.". Note that we are calling the constructor of the parent `User` class using the `super` keyword, passing in the `name` argument. The `Borrower` class does not have any instance variables.

When the user of the software specifies action 4, your program must ask the user to type the name of a user, and a number of books, and the program then uses that number to increase the number of books lent or borrowed by the user. Then the program goes back to the main menu.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). Note that, even if a consumer is a borrower, the readPosInt method prevents the typed number of books from being negative. This means a borrower will never throw a NotALenderException. Nevertheless the code of the main method of your CLI class must handle this exception by printing the error message "BUG! This must never happen!" and immediately terminating the program using System.exit(1).

Here's an example implementation of the main method of the CLI class that follows the above requirements: ```java import java.util.Scanner; public class CLI { private static final Scanner scanner = new Scanner(System.in); private static final Library library = new Library(); public static void main(String[] args) { while (true) { printMenu(); int action = readPosInt("Type an action number:"); try { switch (action) { case 1: System.out.println(library.listBooks()); break; case 2: String author = readString("Type an author name:"); System.out.println(library.listBooksByAuthor(author)); break; case 3: String title = readString("Type a book title:"); System.out.println(library.findBook(title)); break; case 4: String user = readString("Type a user name:"); int numBooks = readPosInt("Type a number of books:"); library.lendOrBorrow(user, numBooks); break; case 5: System.exit(0); default: System.out.println("Unknown action number."); break; } } catch (UnknownUserException e) { System.out.println(e.getMessage()); } catch (NotALenderException e) { System.out.println("BUG! This must never happen!"); System.exit(1); } } } private static void printMenu() { System.out.println("Menu:"); System.out.println("[1] List all books"); System.out.println("[2] List books by author"); System.out.println("[3] Find a book by title"); System.out.println("[4] Lend/borrow books for a user"); System.out.println("[5] Quit"); } private static String readString(String prompt) { System.out.println(prompt); return scanner.nextLine().trim(); } private static int readPosInt(String prompt) { int num = -1; while (num <= 0) { System.out.println(prompt); try { num = Integer.parseInt(scanner.nextLine().trim()); } catch (NumberFormatException e) { System.out.println("Invalid number."); } } return num; } } ``` Note that the code uses a `Library` object to perform the actions requested by the user, and catches the `UnknownUserException` and `NotALenderException` exceptions as required.
阅读全文

相关推荐

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. Modify the run method of the GUI class to add a ViewCreate view that uses a ControllerCreate controller and the same model as before (not a new model!) Do not delete the previous views. Note: if at the end of Question 7 you had manually added to your library (model object) some users for testing, then you must now remove those users from the run method of the anonymous class inside the GUI class. You do not need these test users anymore because you have now a graphical user interface to create new users! Run your GUI and check that you can correctly use the new view to create different users for your library, with different types of roles. • Check that, when you create a new user, the simple view is automatically correctly updated to show the new total number of books borrowed by all users. • Also use the “get book” view to check that the users are correctly created with the correct names and correct number of books. • Also check that trying to create a borrower with a negative number of books correctly shows an error message. Also check that trying to create a user with a number of books which is not an integer correctly shows an error message (do not worry about the content of the error message). After you created a new user, you can also check whether it is a lender or a borrower using the “more book” view to increase the number of books of the user by a big negative number: • if the new user you created is a lender, then increasing the number of books by a big negative value will work and the number of books borrowed by the user will just become a larger value (you can then check that using the “get book” view); • if the new user you created is a borrower, then increasing the number of books by a big negative value will fail with an error message and the number of books borrowed by the user will not change (you can then check that using the “get book” view). 完成符合以上要求的java代码

Also create a ControllerMoreBook class that extends Controller.The moreBook method takes the name of a user and a number of books (as a string) as arguments. The moreBook method of the controller then transforms the number of books from a string to an integer (using the Integer.parseInt static method) and calls the moreBook method of the library to increase the number of books borrowed or lent by the user (depending on what kind of user it is) of a specific user, by the given argument. • If no exception occurs then the moreBook method of the controller returns the empty string. • If the moreBook method of the library throws an UnknownUserException then the moreBook method of the controller must catch this exception and return as result the error message from the exception object. • If the moreBook method of the library throws a NotALenderException then the moreBook 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 moreBook method of the controller must catch this exception and return as result the error message from the exception object. Note: to keep things simple, it is allowed for a user of your system to increase the number of books of a user by a negative number, so there is no need to check for that. Modify the run method of the GUI class to add a ViewMoreBook view that uses a ControllerMoreBook controller and the same model as before (not a new model!) Do not delete the previous views. Run your GUI and check that you can correctly use the new view to increase the number of books for different users of your library (obviously your library must have some users in it to test this: see the last paragraph of Question 7). • Check that, when you increase a user’s book, the simple view is automatically correctly updated to show the new total number of borrowed books for all users of the library. • Also use the “get book” view to check that the user’s book value correctly changed. • Also check that increasing the book number of an unknown user correctly shows an error message.Also check that increasing the book of a user by a large negative number correctly shows an error message. Also check that trying to increase the book of a user by a number which is not an integer correctly shows an error message (do not worry about the content of the error message). 完成符合以上要求的java代码

Action 2: adding a new user to the library. When the user of the software specifies action 2, your program must add a new user to the library. To add a new user, your program needs to ask the user three things: the role of user (an integer read using readPosInt: the integer 1 represents lender, the integer 2 represents borrower, any other integer must result in an error message "Unknown user role!" being printed and the software going immediately back to the main menu), the name of the user (a string read using readLine), and the initial number of books that the user lends (for a lender) or borrows (for a borrower). You program must then create the correct user, add it to the library, and print an information message. The program then goes back to the menu. For example (where 2, 3, 2, 1, Anna, 5, 2, 2, Bob, and 10 are inputs from the user): Type an action (total:1 add:2 get:3 more:4 less:5 quit:6): 2 Type the user role (lender:1 borrower:2): 3 Unknown user role! Type an action (total:1 add:2 get:3 more:4 less:5 quit:6): 2 Type the user role (lender:1 borrower:2): 1 Enter the name of the user: Anna Enter the initial number of borrowed books: 5 Lender "Anna" lending 5 book(s) has been added. Type an action (total:1 add:2 get:3 more:4 less:5 quit:6): 2 Type the user role (lender:1 borrower:2): 2 Enter the name of the user: Bob Enter the initial number of borrowed books: 10 Borrower "Bob" borrowing 10 book(s) has been added. Type an action (total:1 add:2 get:3 more:4 less:5 quit:6): Note that the readPosInt method prevents the initial number of books from being negative, so the constructor for the Borrower class will never throw a NotALenderException when you create a borrower object. Nevertheless the code of the main method of your CLI class must handle this exception by printing the error message "BUG! This must never happen!" and immediately terminating the program using System.exit(1);

use java language ,In this project you need to write a book lending system for a Library. The system has different roles for registered users. There are two types of user roles: borrower and lender. Write an IUser interface for library users, with the following UML specification: +----------------------------------+ | <<interface>> | | IUser | +----------------------------------+ | + getName(): String | | + getBook(): int | | + moreBook(int number): void | +----------------------------------+ and a User class that implements IUser and has the following UML specification: +-----------------------------------+ | User | +-----------------------------------+ | - name: String | | - book: int | +-----------------------------------+ | + User(String name, int book) | | + getName(): String | | + getBook(): int | | # setBook(int book): void | | + moreBook(int number): void | | + testUser(): void | +-----------------------------------+ The name instance variable indicates the user name. The book instance variable indicates the number of books borrowed by the user. The setBook method changes the number of books borrowed by the user. The setBook method is protected, not public. This means that only subclasses of the User class can use the setBook method. All the other classes in the system cannot use the setBook method, so they cannot change the number of books borrowed by a user. The purpose of the moreBook method is to increase the number of books borrowed or lent by the user (depending on what kind of user it is) by the number given as argument to the method. The moreBook method of the User class is abstract, since we do not know what kind of role the user is (a borrower borrows books from other users and a lender lend books to other users). Also add to your program a Test class to test your User class. public class Test { public static void main(String[] args) { User.testUser(); } }

帮我修改一下我的代码错误:帮我看看我这段代码有什么错误:int choice = readPosInt("Type an action (total:1 add:2 get:3 more:4 less:5 quit:6): "); // Perform the selected action while (choice != 6) { switch (choice) { case 1: System.out.println("Total number of borrowed books: " + Library.totalBorrowedBooks(null)); break; case 2: System.out.print("Type the user role (lender:1 borrower:2): "); int role = readPosInt(null); if (role == 1) { System.out.print("Enter the name of the user: "); String name = readLine(name); System.out.print("Enter the initial number of lent books: "); int numBooks = readPosInt(null); Lender lender = new Lender(name, numBooks); Library.addUser(lender); System.out.println("Lender "" + name + "" lending " + numBooks + " book(s) has been added."); } else if (role == 2) { System.out.print("Enter the name of the user: "); String name = readLine(name); System.out.print("Enter the initial number of borrowed books: "); int numBooks = readPosInt(null); Borrower borrower = new Borrower(name, numBooks); Library.addUser(borrower); System.out.println("Borrower "" + name + "" borrowing " + numBooks + " book(s) has been added."); } else { System.out.println("Unknown user role!"); } break; case 3: System.out.print("Enter the name of the user: "); String username = input.nextLine(); try { int numBorrowed = Library.totalBorrowedBooks(username); System.out.println(username + " borrows " + numBorrowed + " book(s)."); } catch (UnknownUserException e) { System.out.println("User " + username + " unknown."); } break; case 4: try { System.out.print("Enter the name of the user: "); String name = input.nextLine(); System.out.print("Enter the number of books: "); int num = input.nextInt(); input.nextLine(); library.moreBook(username, role); } catch (UnknownUserException e) { System.out.println("User " + username + " unknown."); } break; case 5: System.out.print("Enter the name of the user: "); username = input.next(); System.out.print("Enter the number of books: "); int numBooks = input.nextInt(); library.moreBook(username, -numBooks); // simulate decreasing books break; case 6: System.out.println("Goodbye!"); System.exit(0); break; }

zip

最新推荐

recommend-type

基于微信小程序的在线办公小程序答辩PPT.pptx

基于微信小程序的在线办公小程序答辩PPT.pptx
recommend-type

机器学习(预测模型):2000年至2015年期间193个国家的预期寿命和相关健康因素的数据

这个数据集来自世界卫生组织(WHO),包含了2000年至2015年期间193个国家的预期寿命和相关健康因素的数据。它提供了一个全面的视角,用于分析影响全球人口预期寿命的多种因素。数据集涵盖了从婴儿死亡率、GDP、BMI到免疫接种覆盖率等多个维度,为研究者提供了丰富的信息来探索和预测预期寿命。 该数据集的特点在于其跨国家的比较性,使得研究者能够识别出不同国家之间预期寿命的差异,并分析这些差异背后的原因。数据集包含22个特征列和2938行数据,涉及的变量被分为几个大类:免疫相关因素、死亡因素、经济因素和社会因素。这些数据不仅有助于了解全球健康趋势,还可以辅助制定公共卫生政策和社会福利计划。 数据集的处理包括对缺失值的处理、数据类型转换以及去重等步骤,以确保数据的准确性和可靠性。研究者可以使用这个数据集来探索如教育、健康习惯、生活方式等因素如何影响人们的寿命,以及不同国家的经济发展水平如何与预期寿命相关联。此外,数据集还可以用于预测模型的构建,通过回归分析等统计方法来预测预期寿命。 总的来说,这个数据集是研究全球健康和预期寿命变化的宝贵资源,它不仅提供了历史数据,还为未来的研究和政策制
recommend-type

基于微信小程序的“健康早知道”微信小程序答辩PPT.pptx

基于微信小程序的“健康早知道”微信小程序答辩PPT.pptx
recommend-type

基于微信小程序的电影交流平台答辩PPT.pptx

基于微信小程序的电影交流平台答辩PPT.pptx
recommend-type

Aspose资源包:转PDF无水印学习工具

资源摘要信息:"Aspose.Cells和Aspose.Words是两个非常强大的库,它们属于Aspose.Total产品家族的一部分,主要面向.NET和Java开发者。Aspose.Cells库允许用户轻松地操作Excel电子表格,包括创建、修改、渲染以及转换为不同的文件格式。该库支持从Excel 97-2003的.xls格式到最新***016的.xlsx格式,还可以将Excel文件转换为PDF、HTML、MHTML、TXT、CSV、ODS和多种图像格式。Aspose.Words则是一个用于处理Word文档的类库,能够创建、修改、渲染以及转换Word文档到不同的格式。它支持从较旧的.doc格式到最新.docx格式的转换,还包括将Word文档转换为PDF、HTML、XAML、TIFF等格式。 Aspose.Cells和Aspose.Words都有一个重要的特性,那就是它们提供的输出资源包中没有水印。这意味着,当开发者使用这些资源包进行文档的处理和转换时,最终生成的文档不会有任何水印,这为需要清洁输出文件的用户提供了极大的便利。这一点尤其重要,在处理敏感文档或者需要高质量输出的企业环境中,无水印的输出可以帮助保持品牌形象和文档内容的纯净性。 此外,这些资源包通常会标明仅供学习使用,切勿用作商业用途。这是为了避免违反Aspose的使用协议,因为Aspose的产品虽然是商业性的,但也提供了免费的试用版本,其中可能包含了特定的限制,如在最终输出的文档中添加水印等。因此,开发者在使用这些资源包时应确保遵守相关条款和条件,以免产生法律责任问题。 在实际开发中,开发者可以通过NuGet包管理器安装Aspose.Cells和Aspose.Words,也可以通过Maven在Java项目中进行安装。安装后,开发者可以利用这些库提供的API,根据自己的需求编写代码来实现各种文档处理功能。 对于Aspose.Cells,开发者可以使用它来完成诸如创建电子表格、计算公式、处理图表、设置样式、插入图片、合并单元格以及保护工作表等操作。它也支持读取和写入XML文件,这为处理Excel文件提供了更大的灵活性和兼容性。 而对于Aspose.Words,开发者可以利用它来执行文档格式转换、读写文档元数据、处理文档中的文本、格式化文本样式、操作节、页眉、页脚、页码、表格以及嵌入字体等操作。Aspose.Words还能够灵活地处理文档中的目录和书签,这让它在生成复杂文档结构时显得特别有用。 在使用这些库时,一个常见的场景是在企业应用中,需要将报告或者数据导出为PDF格式,以便于打印或者分发。这时,使用Aspose.Cells和Aspose.Words就可以实现从Excel或Word格式到PDF格式的转换,并且确保输出的文件中不包含水印,这提高了文档的专业性和可信度。 需要注意的是,虽然Aspose的产品提供了很多便利的功能,但它们通常是付费的。用户需要根据自己的需求购买相应的许可证。对于个人用户和开源项目,Aspose有时会提供免费的许可证。而对于商业用途,用户则需要购买商业许可证才能合法使用这些库的所有功能。"
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【R语言高性能计算秘诀】:代码优化,提升分析效率的专家级方法

![R语言](https://www.lecepe.fr/upload/fiches-formations/visuel-formation-246.jpg) # 1. R语言简介与计算性能概述 R语言作为一种统计编程语言,因其强大的数据处理能力、丰富的统计分析功能以及灵活的图形表示法而受到广泛欢迎。它的设计初衷是为统计分析提供一套完整的工具集,同时其开源的特性让全球的程序员和数据科学家贡献了大量实用的扩展包。由于R语言的向量化操作以及对数据框(data frames)的高效处理,使其在处理大规模数据集时表现出色。 计算性能方面,R语言在单线程环境中表现良好,但与其他语言相比,它的性能在多
recommend-type

在构建视频会议系统时,如何通过H.323协议实现音视频流的高效传输,并确保通信的稳定性?

要通过H.323协议实现音视频流的高效传输并确保通信稳定,首先需要深入了解H.323协议的系统结构及其组成部分。H.323协议包括音视频编码标准、信令控制协议H.225和会话控制协议H.245,以及数据传输协议RTP等。其中,H.245协议负责控制通道的建立和管理,而RTP用于音视频数据的传输。 参考资源链接:[H.323协议详解:从系统结构到通信流程](https://wenku.csdn.net/doc/2jtq7zt3i3?spm=1055.2569.3001.10343) 在构建视频会议系统时,需要合理配置网守(Gatekeeper)来提供地址解析和准入控制,保证通信安全和地址管理
recommend-type

Go语言控制台输入输出操作教程

资源摘要信息:"在Go语言(又称Golang)中,控制台的输入输出是进行基础交互的重要组成部分。Go语言提供了一组丰富的库函数,特别是`fmt`包,来处理控制台的输入输出操作。`fmt`包中的函数能够实现格式化的输入和输出,使得程序员可以轻松地在控制台显示文本信息或者读取用户的输入。" 1. fmt包的使用 Go语言标准库中的`fmt`包提供了许多打印和解析数据的函数。这些函数可以让我们在控制台上输出信息,或者从控制台读取用户的输入。 - 输出信息到控制台 - Print、Println和Printf是基本的输出函数。Print和Println函数可以输出任意类型的数据,而Printf可以进行格式化输出。 - Sprintf函数可以将格式化的字符串保存到变量中,而不是直接输出。 - Fprint系列函数可以将输出写入到`io.Writer`接口类型的变量中,例如文件。 - 从控制台读取信息 - Scan、Scanln和Scanf函数可以读取用户输入的数据。 - Sscan、Sscanln和Sscanf函数则可以从字符串中读取数据。 - Fscan系列函数与上面相对应,但它们是将输入读取到实现了`io.Reader`接口的变量中。 2. 输入输出的格式化 Go语言的格式化输入输出功能非常强大,它提供了类似于C语言的`printf`和`scanf`的格式化字符串。 - Print函数使用格式化占位符 - `%v`表示使用默认格式输出值。 - `%+v`会包含结构体的字段名。 - `%#v`会输出Go语法表示的值。 - `%T`会输出值的数据类型。 - `%t`用于布尔类型。 - `%d`用于十进制整数。 - `%b`用于二进制整数。 - `%c`用于字符(rune)。 - `%x`用于十六进制整数。 - `%f`用于浮点数。 - `%s`用于字符串。 - `%q`用于带双引号的字符串。 - `%%`用于百分号本身。 3. 示例代码分析 在文件main.go中,可能会包含如下代码段,用于演示如何在Go语言中使用fmt包进行基本的输入输出操作。 ```go package main import "fmt" func main() { var name string fmt.Print("请输入您的名字: ") fmt.Scanln(&name) // 读取一行输入并存储到name变量中 fmt.Printf("你好, %s!\n", name) // 使用格式化字符串输出信息 } ``` 以上代码首先通过`fmt.Print`函数提示用户输入名字,并等待用户从控制台输入信息。然后`fmt.Scanln`函数读取用户输入的一行信息(包括空格),并将其存储在变量`name`中。最后,`fmt.Printf`函数使用格式化字符串输出用户的名字。 4. 代码注释和文档编写 在README.txt文件中,开发者可能会提供关于如何使用main.go代码的说明,这可能包括代码的功能描述、运行方法、依赖关系以及如何处理常见的输入输出场景。这有助于其他开发者理解代码的用途和操作方式。 总之,Go语言为控制台输入输出提供了强大的标准库支持,使得开发者能够方便地处理各种输入输出需求。通过灵活运用fmt包中的各种函数,可以轻松实现程序与用户的交互功能。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依