图书借取异常的实现

package com.exception;
import java.util.InputMismatchException;
import java.util.Scanner;
public class Borrow {
	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args){
		// TODO Auto-generated method stub
		int d=0;
		do{
			try{
				d=cin();
			}catch(ChooseException e){//抛出选择异常
				System.out.println(e.getMessage());
			}catch(InputMismatchException e){//输入数据类型错误
				System.out.println(e.getMessage());
			}catch(Exception e){
				System.out.println(e.getMessage());
			}
		}while(d!=1);
		System.out.println("图书借取成功!");
	}
	
	public static int cin() throws Exception {
		Book[] book =new Book[]{
				new Book("高数",1),
				new Book("英语",2),
				new Book("物理",3)
			};
		System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书");
		Scanner in =new Scanner(System.in);
		int h=in.nextInt();
		//1为名称入口 2为ID入口 其他抛出选择错误
		if(h==1){
			System.out.println("输入图书名称:");
			String name = in.next();
			for(Book b:book){//选中返回1 没选中抛出图书不存在异常
				if(b.getName().equals(name)){
					System.out.println("book:"+b.getName());
					return 1;
				}
			}
			throw new ChooseException("图书不存在");
		}else if(h==2){
			System.out.println("输入图书序号:");
			int id = in.nextInt();
			for(Book b:book){//选中返回1 没选中抛出图书不存在异常
				if(b.getId()==id){
					System.out.println("book:"+b.getName());
					return 1;
				}
			}
			throw new ChooseException("图书不存在");
		}else{
			throw new ChooseException("命令输入错误!请根据提示输入数字命令");
		}
	}

}
/**
 * 书本类
 */
 class Book{
	private String name;
	private int id;
	public Book(){
		
	}
	public Book(String bookName,int id){
		this.name = bookName;
		this.id = id;
	}
	public void setName(String name){
		this.name = name;
	}
	public String getName(){
		return name;
	}
	public void setId(int id){
		this.id =id;
	}
	public int getId(){
		return id;
	}
}
 
 /**选择异常*/
 class ChooseException extends Exception{
	 public ChooseException(){
		 
	 }
	 public ChooseException(String message){
		 super(message);
	 }
 }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值