Home Java javaTutorial Detailed explanation of the steps to simulate the book borrowing system using Java exception mechanism

Detailed explanation of the steps to simulate the book borrowing system using Java exception mechanism

May 09, 2017 am 11:37 AM
java

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) {

  // 异常处理代码

}
Copy after login

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

Reference code and Comments

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;
 }
 }
}
Copy after login

Summary

【Related recommendations】

1.

Java Free Video Tutorial

2.

YMP Online Manual

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

How to Run Your First Spring Boot Application in Spring Tool Suite? How to Run Your First Spring Boot Application in Spring Tool Suite? Feb 07, 2025 pm 12:11 PM

Spring Boot simplifies the creation of robust, scalable, and production-ready Java applications, revolutionizing Java development. Its "convention over configuration" approach, inherent to the Spring ecosystem, minimizes manual setup, allo

See all articles