package com.imooc.test; //import java.util.InputMismatchException; import java.util.Scanner; public class LibrarySystem { public static void main(String[] args) { // TODO Auto-generated method stub String[] bookName={"高数","线代","思修","信号与系统"}; while(true){ Scanner input=new Scanner(System.in);//创建Scanner对象 System.out.println("欢迎来到图书管理系统!"); System.out.println("输入命令:1-按照名称查找图书;2-按照序号查找图书"); try{ int cmd=input.nextInt(); String book; switch(cmd){ case 1: System.out.println("请输入图书名称:"); book= bookname(bookName); System.out.println("book:"+book); break; case 2: System.out.println("请输入图书序号:"); book= booknum(bookName); System.out.println("book:"+book); break; } }catch (Exception e){ System.out.println("图书不存在!"); } } } public static String bookname(String[] book)throws Exception{ Scanner input=new Scanner(System.in);//创建Scanner对象 // System.out.println("输入图书名称:"); String cmd1=input.next(); for(int i=0;i<book.length;i++){ if(cmd1.equals(book[i])) return book[i]; } throw new Exception("图书不存在!"); } public static String booknum(String[] book)throws Exception{ Scanner input=new Scanner(System.in);//创建Scanner对象 //System.out.println("输入图书序号:"); int cmd2=input.nextInt(); if((cmd2>=0)&&(cmd2<book.length)){ return book[cmd2]; } throw new Exception("图书不存在!");} }
我是初学者,觉得你写得非常好,还可以再改进改进,多分享,共同进步。