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<Book> listBooks;
//无参构造方法
public BorrowBook() {
this.listBooks = new ArrayList<Book>();
}
public void addBook(){
listBooks.addAll(Arrays.asList(book));
}
public void systemOut() {
System.out.println("*******欢迎使用借书系统*******");
System.out.println("*-*-*-*图书一览表:*-*-*-*");
System.out.println(" 书名" + "\t\t" + "序号");
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;
}
}
}
以上是 Java异常之图书管理系统 的全部内容, 来源链接: utcz.com/z/327772.html