1.创建书大类
public class Book { private String name; private int num; public Book(String name,int num){ this.name=name; this.num=num; } public String getName(){ return name; } public void setName(String name){ this.name=name; } public int getNum(){ return num; } public void setNum(int num){ this.num=num; } }
2.自定义异常
public class NoExistException extends Exception{ public NoExistException(String message){ super(message); } public NoExistException(){ } }
3.主程序
import java.util.*; public class Test2 { private Scanner input = new Scanner(System.in); Book[] book={ new Book("语文",1), new Book("数学",2), new Book("英语",3), new Book("专业课",4) }; // public List<Book> listbooks; // public Test2() { // this.listbooks = new ArrayList<Book>(); // } // public void listBooksAdd() { // listbooks.addAll(Arrays.asList(book)); // } public void printbook(){ System.out.println("====欢迎使用选书系统===="); System.out.println("=====书本信息如下:====="); System.out.println("序号"+"\t"+"书名"); for(Book bk:book){ System.out.println(bk.getNum()+"\t"+bk.getName()); } } public static void main(String[] args) { Test2 tc=new Test2(); // tc.listBooksAdd(); tc.printbook(); while(true){ System.out.println("请选择查书方式1-通过序号2-通过书名:"); switch(tc.back()){ case 1: try{ System.out.println("您的书为:"+tc.fbid()); break; }catch(Exception e){ System.out.println(e.getMessage()); continue; } case 2: try{ System.out.println("您的书为:"+tc.fbbn()); break; }catch(Exception e){ System.out.println(e.getMessage()); continue; } default: System.out.println("输入错误!请重新输入!!!"); continue; }break; } } public String fbid() throws NoExistException{ System.out.println("请输入图书的序号:"); int in=input.nextInt(); for(Book bk:book){ if(in==bk.getNum()){ return book[in-1].getName(); } } throw new NoExistException("序号越界请重新输入"); } public String fbbn()throws NoExistException{ System.out.println("请输入图书的书名:"); String in=input.next(); for(Book bk:book){ if(in.equals(bk.getName())){ return bk.getName(); } } throw new NoExistException("此书不存在"); } public int back(){ int in=input.nextInt(); return in; } }
时间: 2024-10-11 17:56:10