Java图书查询系统实例

这个系统主要涉及 #面向对象#错误测试。

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.自定义一个Exception

public class NoExistException extends Exception {
public NoExistException(String message){
	super(message);
}
}

 3.主程序

import java.util.*;
public class Test {
	 Book[] book = {new Book("语文",1),
			 new Book("数学",2),
			 new Book("外语",3), 
			 new Book("Java编程",4)
	 }; 
	 public List<Book> listbooks;
	 public Test() { 
		 this.listbooks = new ArrayList<Book>(); 
		 } 
	 public void listBooksAdd() { 
		 listbooks.addAll(Arrays.asList(book)); 
		 } 
	 public void printBooks() { 
			 System.out.println("---------- 欢迎使用借书系统 ----------"); 
			 System.out.println("图书列表展示如下:"); System.out.println("序号" + "\t" + "书名");
			 for (Book bk : listbooks) { 
				 System.out.println(bk.getNum() + "\t" + bk.getName()); 
			 } 
			 }
	 private Scanner input = new Scanner(System.in);
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		 		Test fb=new Test();
		 fb.listBooksAdd();
		 fb.printBooks(); 
		 System.out.println();
		 while(true){
			 System.out.println("请输入您的命令:1.按名称查找\t2.按序号查找");
			 switch(fb.wr()){
			 case 2:
				try{
					System.out.println("book:"+fb.fbid());
					break;
				}catch(Exception e){
					System.out.println(e.getMessage());
					continue;
				}
			 case 1:
				 try{
					 System.out.println("book:"+fb.fbbn());
					 break;
				 }catch(Exception e){
					 System.out.println(e.getMessage());
					 continue;
				 }
			 default:
				 System.out.println("错误,请重新输入");
				 continue;
			 }
		 }

	 
	}
public String fbid()throws NoExistException{
	System.out.println("请输入书 的序号");
	int in=input.nextInt();
	for(Book bk : listbooks){
		if(in==bk.getNum()){
			return book[in-1].getName();
		}
	}
	throw new NoExistException("序号越界,此书籍不存在!!!");
}

public String fbbn()throws NoExistException{
	System.out.println("请输入书的名称");
	String bname=input.next();
	for(Book bk:listbooks){
		if(bname.equals(bk.getName())){
		return bk.getName();	
		}
	}
	throw new NoExistException("名称错误,此书籍不存在!!!");
}
public int wr(){
	try{
		int in=input.nextInt();
		return in;
	}catch(Exception e){
	return -1;	
	}
}
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值