图书查询系统 java_图书查询系统(java异常学习)

图书类:

public class Book {

String name = "";

int id = -1;

public Book (int id, String name) {

this.id = id;

this.name = name;

}

public String getName() {

return name;

}

public int getId() {

return id;

}

}

图书异常类:

public class BookException extends Exception {

public BookException () {}

public BookException (String message) {

super (message);

}

}

函数体:

import java.util.*;

public class Initial {

public int getCommand () throws BookException {

Scanner input = new Scanner (System.in);

int command;

try {

command = input.nextInt();

} catch (Exception e) {

throw new BookException("错误命令异常");

}

if (command < 0 command >2) {

throw new BookException("错误命令异常");

}

return command;

}

public Book searchFromName (Book books[]) throws BookException {

Scanner input = new Scanner (System.in);

System.out.println ("请输入图书名称:");

String name = input.next();

for (int i = 0; i < books.length; i++) {

if (books[i].getName().equals(name)) {

return books[i];

}

}

throw new BookException ("图书不存在异常");

}

public Book searchFromID (Book books[]) throws BookException {

Scanner input = new Scanner (System.in);

System.out.println ("请输入图书序号:");

int id;

try {

id = input.nextInt();

} catch (Exception e) {

throw new BookException("错误命令异常");

}

for (int i = 0; i < books.length; i++) {

if (books[i].getId() == id) {

return books[i];

}

}

throw new BookException ("图书不存在异常");

}

public void startSearch () {

Book books [] = {new Book (1, "高数"),

new Book (2, "线代"),

new Book (3, "C语言"),

new Book (4, "Java"),};

int command;

Book target;

while (true) {

System.out.println ("输入命令:0-退出;1-按照名称查找图书;2-按照序号查找图书");

try {

command = getCommand();

} catch (Exception e) {

System.out.println (e.getMessage());

continue;

}

switch (command) {

case 0:

return;

case 1:

try {

target = searchFromName (books);

} catch (Exception e) {

System.out.println (e.getMessage());

continue;

}

System.out.println ("查找成功!图书序号:"+target.getId()+"\t图书名称:" +target.getName());

break;

case 2:

try {

target = searchFromID (books);

} catch (Exception e) {

System.out.println (e.getMessage());

continue;

}

System.out.println ("查找成功!图书序号:"+target.getId()+"\t图书名称:" +target.getName());

break;

}

}

}

public static void main(String[] args) {

// TODO Auto-generated method stub

Initial init = new Initial ();

System.out.println ("******欢迎进入图书查询系统!******");

init.startSearch();

System.out.println ("******谢谢使用,再见!******");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值