主要是会用这个自定义异常吧
book类
package Eception; public class book { private int id; private String name; public book(int id,String name) { this.id=id; this.name=name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
借书类
package Eception; import java.util.Scanner; public class BorrowBooks { book[] books= {new book(1,"高数"), new book(2,"英语"), new book(3,"数据结构") }; Scanner scan=new Scanner(System.in); public static void main(String[]args) { BorrowBooks b=new BorrowBooks(); b.BorrowBook(); //scan.close(); } public void BorrowBook() { System.out.println("输入命令:1.按名称查找图书 2.按序号查找图书:3.退出"); String a=scan.next(); try { if(a.equals("1")) { mingcheng(); } else if(a.equals("2")) { xuhao(); } else if(a.equals("3")) { scan.close(); System.out.println("退出成功!"); } else { throw new Errororders("命令错误,请重新输入"); } }catch(Errororders e){ System.out.println(e.getMessage()); //e.printStackTrace(); BorrowBook(); } } public void mingcheng() { System.out.println("输入图书的名称"); String s=scan.next(); int a=-1; for(int i=0;i<books.length;i++) { if(s.equals(books[i].getName())) { a=1; System.out.println("book序号:"+books[i].getId()); BorrowBook(); } } if(a==-1) { try { throw new Errororders("该图书不存在!"); } catch (Errororders e) { // TODO Auto-generated catch block //e.printStackTrace(); System.out.println(e.getMessage()); BorrowBook(); } } } public void xuhao() { System.out.println("输入图书的序号"); int s=scan.nextInt(); int a=-1; for(int i=0;i<books.length;i++) { //System.out.println("图书名称!:"+books[i].getId()); if(s==books[i].getId()) { a=1; System.out.println("图书名称:"+books[i].getName()); BorrowBook(); } } if(a==-1) { try { throw new Errororders("该序号不存在!"); } catch (Errororders e) { // TODO Auto-generated catch block //e.printStackTrace(); System.out.println(e.getMessage()); BorrowBook(); } } } }
自定义的异常Errororders
package Eception; public class Errororders extends Exception { public Errororders() { } public Errororders(String message) { super(message); } }