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 20:01:51 浏览: 117
根据您提供的问题,我猜测您想问的是,如何在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; }

最新推荐

recommend-type

数学建模拟合与插值.ppt

数学建模拟合与插值.ppt
recommend-type

[net毕业设计]ASP.NET教育报表管理系统-权限管理模块(源代码+论文).zip

【项目资源】:包含前端、后端、移动开发、操作系统、人工智能、物联网、信息化管理、数据库、硬件开发、大数据、课程资源、音视频、网站开发等各种技术项目的源码。包括STM32、ESP8266、PHP、QT、Linux、iOS、C++、Java、python、web、C#、EDA、proteus、RTOS等项目的源码。【项目质量】:所有源码都经过严格测试,可以直接运行。功能在确认正常工作后才上传。【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。【附加价值】:项目具有较高的学习借鉴价值,也可直接拿来修改复刻。对于有一定基础或热衷于研究的人来说,可以在这些基础代码上进行修改和扩展,实现其他功能。【沟通交流】:有任何使用上的问题,欢迎随时与博主沟通,博主会及时解答。鼓励下载和使用,并欢迎大家互相学习,共同进步。
recommend-type

mysql相关资源.txt

mysql相关资源.txt
recommend-type

利用HTML+CSS+JS的国漫分享网站(响应式)

此项目为一个HTML+CSS+JS的国漫分享网站,用户可以在此网站中观看自己喜欢的国漫。此网站共有4个页面,分别为首页,最新动态,热门推荐,分类。页面动漫图片齐全,内容可更改。可用于期末课程设计或个人课程设计。
recommend-type

火炬连体网络在MNIST的2D嵌入实现示例

资源摘要信息:"Siamese网络是一种特殊的神经网络,主要用于度量学习任务中,例如人脸验证、签名识别或任何需要判断两个输入是否相似的场景。本资源中的实现例子是在MNIST数据集上训练的,MNIST是一个包含了手写数字的大型数据集,广泛用于训练各种图像处理系统。在这个例子中,Siamese网络被用来将手写数字图像嵌入到2D空间中,同时保留它们之间的相似性信息。通过这个过程,数字图像能够被映射到一个欧几里得空间,其中相似的图像在空间上彼此接近,不相似的图像则相对远离。 具体到技术层面,Siamese网络由两个相同的子网络构成,这两个子网络共享权重并且并行处理两个不同的输入。在本例中,这两个子网络可能被设计为卷积神经网络(CNN),因为CNN在图像识别任务中表现出色。网络的输入是成对的手写数字图像,输出是一个相似性分数或者距离度量,表明这两个图像是否属于同一类别。 为了训练Siamese网络,需要定义一个损失函数来指导网络学习如何区分相似与不相似的输入对。常见的损失函数包括对比损失(Contrastive Loss)和三元组损失(Triplet Loss)。对比损失函数关注于同一类别的图像对(正样本对)以及不同类别的图像对(负样本对),鼓励网络减小正样本对的距离同时增加负样本对的距离。 在Lua语言环境中,Siamese网络的实现可以通过Lua的深度学习库,如Torch/LuaTorch,来构建。Torch/LuaTorch是一个强大的科学计算框架,它支持GPU加速,广泛应用于机器学习和深度学习领域。通过这个框架,开发者可以使用Lua语言定义模型结构、配置训练过程、执行前向和反向传播算法等。 资源的文件名称列表中的“siamese_network-master”暗示了一个主分支,它可能包含模型定义、训练脚本、测试脚本等。这个主分支中的代码结构可能包括以下部分: 1. 数据加载器(data_loader): 负责加载MNIST数据集并将图像对输入到网络中。 2. 模型定义(model.lua): 定义Siamese网络的结构,包括两个并行的子网络以及最后的相似性度量层。 3. 训练脚本(train.lua): 包含模型训练的过程,如前向传播、损失计算、反向传播和参数更新。 4. 测试脚本(test.lua): 用于评估训练好的模型在验证集或者测试集上的性能。 5. 配置文件(config.lua): 包含了网络结构和训练过程的超参数设置,如学习率、批量大小等。 Siamese网络在实际应用中可以广泛用于各种需要比较两个输入相似性的场合,例如医学图像分析、安全验证系统等。通过本资源中的示例,开发者可以深入理解Siamese网络的工作原理,并在自己的项目中实现类似的网络结构来解决实际问题。"
recommend-type

管理建模和仿真的文件

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

L2正则化的终极指南:从入门到精通,揭秘机器学习中的性能优化技巧

![L2正则化的终极指南:从入门到精通,揭秘机器学习中的性能优化技巧](https://img-blog.csdnimg.cn/20191008175634343.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MTYxMTA0NQ==,size_16,color_FFFFFF,t_70) # 1. L2正则化基础概念 在机器学习和统计建模中,L2正则化是一个广泛应用的技巧,用于改进模型的泛化能力。正则化是解决过拟
recommend-type

如何构建一个符合GB/T19716和ISO/IEC13335标准的信息安全事件管理框架,并确保业务连续性规划的有效性?

构建一个符合GB/T19716和ISO/IEC13335标准的信息安全事件管理框架,需要遵循一系列步骤来确保信息系统的安全性和业务连续性规划的有效性。首先,组织需要明确信息安全事件的定义,理解信息安全事态和信息安全事件的区别,并建立事件分类和分级机制。 参考资源链接:[信息安全事件管理:策略与响应指南](https://wenku.csdn.net/doc/5f6b2umknn?spm=1055.2569.3001.10343) 依照GB/T19716标准,组织应制定信息安全事件管理策略,明确组织内各个层级的角色与职责。此外,需要设置信息安全事件响应组(ISIRT),并为其配备必要的资源、
recommend-type

Angular插件增强Application Insights JavaScript SDK功能

资源摘要信息:"Microsoft Application Insights JavaScript SDK-Angular插件" 知识点详细说明: 1. 插件用途与功能: Microsoft Application Insights JavaScript SDK-Angular插件主要用途在于增强Application Insights的Javascript SDK在Angular应用程序中的功能性。通过使用该插件,开发者可以轻松地在Angular项目中实现对特定事件的监控和数据收集,其中包括: - 跟踪路由器更改:插件能够检测和报告Angular路由的变化事件,有助于开发者理解用户如何与应用程序的导航功能互动。 - 跟踪未捕获的异常:该插件可以捕获并记录所有在Angular应用中未被捕获的异常,从而帮助开发团队快速定位和解决生产环境中的问题。 2. 兼容性问题: 在使用Angular插件时,必须注意其与es3不兼容的限制。es3(ECMAScript 3)是一种较旧的JavaScript标准,已广泛被es5及更新的标准所替代。因此,当开发Angular应用时,需要确保项目使用的是兼容现代JavaScript标准的构建配置。 3. 安装与入门: 要开始使用Application Insights Angular插件,开发者需要遵循几个简单的步骤: - 首先,通过npm(Node.js的包管理器)安装Application Insights Angular插件包。具体命令为:npm install @microsoft/applicationinsights-angularplugin-js。 - 接下来,开发者需要在Angular应用的适当组件或服务中设置Application Insights实例。这一过程涉及到了导入相关的类和方法,并根据Application Insights的官方文档进行配置。 4. 基本用法示例: 文档中提到的“基本用法”部分给出的示例代码展示了如何在Angular应用中设置Application Insights实例。示例中首先通过import语句引入了Angular框架的Component装饰器以及Application Insights的类。然后,通过Component装饰器定义了一个Angular组件,这个组件是应用的一个基本单元,负责处理视图和用户交互。在组件类中,开发者可以设置Application Insights的实例,并将插件添加到实例中,从而启用特定的功能。 5. TypeScript标签的含义: TypeScript是JavaScript的一个超集,它添加了类型系统和一些其他特性,以帮助开发更大型的JavaScript应用。使用TypeScript可以提高代码的可读性和可维护性,并且可以利用TypeScript提供的强类型特性来在编译阶段就发现潜在的错误。文档中提到的标签"TypeScript"强调了该插件及其示例代码是用TypeScript编写的,因此在实际应用中也需要以TypeScript来开发和维护。 6. 压缩包子文件的文件名称列表: 在实际的项目部署中,可能会用到压缩包子文件(通常是一些JavaScript库的压缩和打包后的文件)。在本例中,"applicationinsights-angularplugin-js-main"很可能是该插件主要的入口文件或者压缩包文件的名称。在开发过程中,开发者需要确保引用了正确的文件,以便将插件的功能正确地集成到项目中。 总结而言,Application Insights Angular插件是为了加强在Angular应用中使用Application Insights Javascript SDK的能力,帮助开发者更好地监控和分析应用的运行情况。通过使用该插件,可以跟踪路由器更改和未捕获异常等关键信息。安装与配置过程简单明了,但是需要注意兼容性问题以及正确引用文件,以确保插件能够顺利工作。
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。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依