Flask接口签名sign原理与实例代码浅析
239
2022-11-11
Java异常之图书管理系统
本文实例为大家分享了java异常之图书管理系统的具体代码,供大家参考,具体内容如下
模拟借书系统,任务要求:
感觉自己的写出来的代码不够简洁,参考了其他的案例写了一个,效果如下:
结构:
运行异常1:
运行异常2:
运行异常3:
正常运行:
1、名称查询
2、序号查询:
Book.java:
package com.tony;
/*
* 图书租赁系统
*/
public class Book {
public String bookName;
public int bookId;
public Book(String bookName, int bookId){
this.bookName = bookName;
this.bookId = bookId;
}
}
自定义异常类MyException.java:
package com.tony;
/*
* 自定义异常类
*/
public class MyException extends Exception{
//有参构造方法
public MyException(String message) {
super(message);
};
}
BorrowBook.java:
package com.tony;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
/*
* 主程序
*/
public class BorrowBook {
Book book [] = {new Book("高等数学", 1), new Book("大学英语", 2), new Book("android", 3), new Book("会计基础", 4)};
public List
//无参构造方法
public BorrowBook() {
this.listBooks = new ArrayList
}
public void addBook(){
listBooks.addAll(Arrays.asList(book));
}
public void systemOut() {
System.out.println("*******欢迎使用借书系统*******");
System.out.println("*-*-*-*图书一览表:*-*-*-*");
System.out.println(" 书名" + "\tt" + "序号");
for(Book book:listBooks) {
System.out.println(book.bookName + "\t\t " +book.bookId);
}
}
private Scanner scanner = new Scanner(System.in);
public static void main(String[] args) {
BorrowBook borrowBook = new BorrowBook();
borrowBook.addBook();
borrowBook.systemOut();
while(true) {
System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
switch (borrowBook.scanf()) {
case 1://根据用户不同的输入内容执行
try {
System.out.println("书籍:" + borrowBook.findByName());
break;
} catch (Exception e) {
System.out.println(e.getMessage());
continue;
}
case 2:
try {
System.out.println("书籍:" + borrowBook.findById());
break;
} catch (Exception e) {
System.out.println(e.getMessage());
continue;
}
default:
System.out.println("命令错误,请重试.");
continue;
}
break;
}
borrowBook.scanner.close();
}
public String findByName() throws MyException{
System.out.println("*****请输入书籍的名称-->");
String name = scanner.next();
for (Book books : book) {
if (name.equals(books.bookName)) {
return books.bookName + "\t序号:" +books.bookId;
}
}
throw new MyException("名称错误,请重试.");
}
public String findById() throws MyException {
System.out.println("*****请输入书籍的序号-->");
int in = scanner.nextInt();
for (int i = 0; i < book.length; i++) {
if (in == (i + 1)) {
return book[i].bookName + "\t序号:" + (i+1);
}
}
throw new MyException("下标越界,请重试.");
}
public int scanf() {
try {
int in = scanner.nextInt();
return in;
} catch(Exception e) {
scanner = new Scanner(System.in);
return -1;
}
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~