java后端模拟借书系统

系统实现代码

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 = { "高数", "语文", "英语", "政治", "历史", "地理" };
		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:
					System.out.println(" 命令输入错误 根据提示输入数字命令 return -1 未输入整数");
					continue;
				default:
					System.out.println("应该在12中选取");
					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();
				if(index == -1){
					System.out.println("输入的不是整数 根据提示输入数字");
					continue;
				}
				String book = books[index+1];
				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);
			//如果输入的第一个数据不是整数 再次输入数据
			return -1;
		}
	}
}

系统运行截图 

猜你喜欢

转载自blog.csdn.net/idiot2B/article/details/87294828