package com.imooc.proj_1;

import java.util.Scanner;

public class BookManagerEasy {
	private static Scanner console = new Scanner(System.in);

	public static void main(String[] args) {
		//¶¨Òå¡±Í¼Êé¡°Êý×é
		String[] books = { "CÓïÑÔ", "Êý¾Ý½á¹¹", "»ã±àÓïÑÔ", "¸ßÊý", "´óÑ§ÓïÎÄ", "Ã«¸Å" };
		while (true) {
			System.out.println("ÊäÈëÃüÁî£º1-°´ÕÕÃû³Æ²éÕÒÍ¼Êé£»2-°´ÕÕÐòºÅ²éÕÒÍ¼Êé");
			String book;
			try {
				//È¡µÃÕûÐÍÃüÁî
				int command = inputCommand();
				//¸ù¾Ý²»Í¬ÃüÁîÖµ£¬½øÐÐ²»Í¬²Ù×÷
				switch (command) {
				case 1://°´ÕÕÍ¼ÊéÃû³ÆÑ¡ÔñÍ¼Êé
					book = getBookByName(books);
					System.out.println("book:" + book);
					break;
				case 2://°´ÕÕÍ¼ÊéÐòºÅ£¨Êý×éÏÂ±ê£©Ñ¡ÔñÍ¼Êé
					book = getBookByNumber(books);
					System.out.println("book:" + book);
					break;
				case -1://·µ»ØÖµÎª-1£¬ËµÃ÷ÊäÈëÓÐÎó
					System.out.println("ÃüÁîÊäÈë´íÎó£¡Çë¸ù¾ÝÌáÊ¾ÊäÈëÊý×ÖÃüÁî£¡");
					continue;
				default://ÆäËûÖµµÄÃüÁî¾ùÈÏÎªÊÇ´íÎóÃüÁî
					System.out.println("ÃüÁîÊäÈë´íÎó£¡");
					continue;
				}
				break;//ÍË³ö³ÌÐò
			} catch (Exception bne) {
				//²¶»ñ¡±Í¼Êé²»´æÔÚÒì³£¡°Ê±£¬ÒªÇóÖØÐÂÊäÈëÃüÁî
				System.out.println(bne.getMessage());
				continue;
			} 
		}
	}

	//°´ÕÕÍ¼ÊéÃû³Æ²éÑ¯Í¼Êé
	private static String getBookByName(String[] books)
			throws Exception {
		System.out.println("ÊäÈëÍ¼ÊéÃû³Æ£º");
		//»ñÈ¡ÊäÈëµÄÍ¼ÊéÃû³Æ
		String name = console.next();
		for (int i = 0; i < books.length; i++) {
			if (name.equals(books[i]))
				//ÊäÈëµÄÃû³ÆÓëÄ³Ò»Í¼ÊéÃû³ÆÆ¥Åä£¬·µ»Ø¸ÃÍ¼Êé
				return books[i];
		}
		//ÈôÎÞÆ¥Åä£¬Å×³ö¡±Í¼Êé²»´æÔÚÒì³£¡°
		throw new Exception("Í¼Êé²»´æÔÚ£¡");
	}

	//¸ù¾ÝÍ¼ÊéÐòºÅ£¨Êý×éÏÂ±ê£©²éÑ¯Í¼Êé
	private static String getBookByNumber(String[] books)
			throws Exception {
		while (true) {
			System.out.println("ÊäÈëÍ¼ÊéÐòºÅ£º");
			try {
				//»ñÈ¡ÊäÈëµÄÍ¼ÊéÐòºÅ£¨Êý×éÏÂ±ê£©
				int index = inputCommand();
				//Èô·µ»ØÖµÎª-1
				if(index == -1){
					System.out.println("ÃüÁîÊäÈë´íÎó£¡Çë¸ù¾ÝÌáÊ¾ÊäÈëÊý×ÖÃüÁî£¡");
					continue;
				}
				//Èô²»³öÏÖ¡±Êý×éÏÂ±êÔ½½çÒì³£¡°£¬Ôò·µ»ØÏàÓ¦Î»ÖÃµÄÍ¼Êé
				String book = books[index];
				return book;
			} catch (ArrayIndexOutOfBoundsException e) {
				//ÊäÈëµÄÐòºÅ²»´æÔÚ£¨Òý·¢¡±Êý×éÏÂ±êÔ½½çÒì³£¡°£©£¬ÔòÅ×³ö¡±Í¼Êé²»´æÔÚÒì³£¡°
				Exception bookNotExists = new Exception("Í¼Êé²»´æÔÚ£¡");
				bookNotExists.initCause(e);
				throw bookNotExists;
			}
		}
	}

	//´Ó¿ØÖÆÌ¨ÊäÈëÃüÁî£¬ÓÃÓÚÊäÈëÃüÁîºÍÊäÈëÍ¼ÊéÐòºÅ
	private static int inputCommand(){
		int command;
		try {
			command = console.nextInt();
			return command;
		} catch (Exception e) {
			//ÈôÊäÈë×Ö·ûÐÍ»òÕß×Ö·û´®£¬ÔòÅ×³öÒì³££¬²¶»ñ¸ÃÒì³££¬Å×³ö¡±´íÎóÃüÁîÒì³£¡°
			console = new Scanner(System.in);
			//·µ»Ø-1
			return -1;
		}
	}
}
