


Detailed explanation of the steps to simulate the book borrowing system using Java exception mechanism
This article mainly introduces you to the relevant information on using the Java exception mechanism to implement a simulated book borrowing system. The article first briefly introduces the Java exception mechanism, and then introduces how to implement a console version in the Java language through sample code. Friends who need it can refer to the simulated book borrowing system. Let’s take a look.
This article introduces the use of Java language to implement a console version of the simulated book borrowing system. Before starting the formal content of this article, let us first understand the Java exception mechanism.
What is an exception?
Abnormal, not normal. Exception is the abbreviation of Exception event, so an exception is an event that occurs when the program is running.
Exceptions will affect the continuity of the program and interrupt it. In Java, everything is an object, so to define exceptions, you also need to use objects. The exception object
encapsulates the exception type and the status when an exception occurs in the program.
The throwing exception we often say is to create an exception object and submit it to the running system.
Exception catching mechanism and try-catch
When an exception occurs, we need to know where the exception occurred, so how to locate the exception Where is the source?
In Java, call stack is used to record the order of method calls. When an exception occurs in a Java program, it searches the call stack, hoping to find a specific
block of code to handle it. Just like when we are sick (Exception), we will go to the hospital to see a doctor in a specific subject. For example, in the following figure, mainmethod
calls method0, similarly method0 calls method1, and so on.
In JavaException handling, use try-catch statement. The syntax is:
try { // 可能出现异常的代码 } catch (ExceptionType name) { // 异常处理代码 } catch (ExceptionType name) { // 异常处理代码 }
Okay, let’s start our text.
Achieve the goal
Use java language to implement a console version of the simulated book borrowing system, aiming topracticejava Abnormal mechanism.
Realize the requirements
##Realize the finished product
package com.jinger; import java.util.Scanner;//导入Scanner包 public class BookManagerEasy { private static Scanner console = new Scanner(System.in);//接收系统输入 public static void main(String[] args) { //定义”图书“数组 String[] books = { "C语言", "数据结构", "汇编语言", "高数", "大学语文", "毛概" }; while (true) { System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书"); String book; try { //取得整型命令 int command = inputCommand(); //根据不同命令值,进行不同操作 switch (command) { case 1://按照图书名称选择图书 book = getBookByName(books); System.out.println("book:" + book); break; case 2://按照图书序号(数组下标)选择图书 book = getBookByNumber(books); System.out.println("book:" + book); break; case -1://返回值为-1,说明输入有误 System.out.println("命令输入错误!请根据提示输入数字命令!"); continue; default://其他值的命令均认为是错误命令 System.out.println("命令输入错误!"); continue; } break;//退出程序 } catch (Exception bne) { //捕获“图书不存在异常”时,要求重新输入命令 System.out.println(bne.getMessage()); continue; } } } //按照图书名称查询图书 private static String getBookByName(String[] books) throws Exception { System.out.println("输入图书名称:"); //获取输入的图书名称 String name = console.next(); for (int i = 0; i < books.length; i++) { if (name.equals(books[i])) //输入的名称与某一图书名称匹配,返回该图书 return books[i]; } //若无匹配,抛出”图书不存在异常“ throw new Exception("图书不存在!"); } //根据图书序号(数组下标)查询图书 private static String getBookByNumber(String[] books) throws Exception { while (true) { System.out.println("输入图书序号:"); try { //获取输入的图书序号(数组下标) int index = inputCommand(); //若返回值为-1 if(index == -1){ System.out.println("命令输入错误!请根据提示输入数字命令!"); continue; } //若不出现“数组下标越界异常”,则返回相应位置的图书 String book = books[index]; return book; } catch (ArrayIndexOutOfBoundsException e) { //输入的序号不存在(引发“数组下标越界异常”),则抛出“图书不存在异常” Exception bookNotExists = new Exception("图书不存在!"); bookNotExists.initCause(e); throw bookNotExists; } } } //从控制台输入命令,用于输入命令和输入图书序号 private static int inputCommand(){ int command; try { command = console.nextInt(); return command; } catch (Exception e) { //若输入字符型或者字符串,则抛出异常,捕获该异常,抛出“错误命令异常” console = new Scanner(System.in); //返回-1 return -1; } } }
Summary
【Related recommendations】1. 2. 3.Comprehensive analysis of Java annotations
The above is the detailed content of Detailed explanation of the steps to simulate the book borrowing system using Java exception mechanism. For more information, please follow other related articles on the PHP Chinese website!

JVM handles operating system API differences through JavaNativeInterface (JNI) and Java standard library: 1. JNI allows Java code to call local code and directly interact with the operating system API. 2. The Java standard library provides a unified API, which is internally mapped to different operating system APIs to ensure that the code runs across platforms.

modularitydoesnotdirectlyaffectJava'splatformindependence.Java'splatformindependenceismaintainedbytheJVM,butmodularityinfluencesapplicationstructureandmanagement,indirectlyimpactingplatformindependence.1)Deploymentanddistributionbecomemoreefficientwi

BytecodeinJavaistheintermediaterepresentationthatenablesplatformindependence.1)Javacodeiscompiledintobytecodestoredin.classfiles.2)TheJVMinterpretsorcompilesthisbytecodeintomachinecodeatruntime,allowingthesamebytecodetorunonanydevicewithaJVM,thusfulf

JavaachievesplatformindependencethroughtheJavaVirtualMachine(JVM),whichexecutesbytecodeonanydevicewithaJVM.1)Javacodeiscompiledintobytecode.2)TheJVMinterpretsandexecutesthisbytecodeintomachine-specificinstructions,allowingthesamecodetorunondifferentp

Platform independence in JavaGUI development faces challenges, but can be dealt with by using Swing, JavaFX, unifying appearance, performance optimization, third-party libraries and cross-platform testing. JavaGUI development relies on AWT and Swing, which aims to provide cross-platform consistency, but the actual effect varies from operating system to operating system. Solutions include: 1) using Swing and JavaFX as GUI toolkits; 2) Unify the appearance through UIManager.setLookAndFeel(); 3) Optimize performance to suit different platforms; 4) using third-party libraries such as ApachePivot or SWT; 5) conduct cross-platform testing to ensure consistency.

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),
