手记

JAVA入门第三季项目(图书查找系统)

package com.bookborrow;

import java.util.InputMismatchException;
import java.util.Scanner;

public class Initial {
    private static String[] books={"三国演义","水浒传","红楼梦","西游记"};
    private static boolean flag=true;
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Initial initial=new Initial();
        while(flag){
            try{
                System.out.println("输入命令    1-按照名称查找图书    2-按照序号查找图书");
                Scanner input=new Scanner(System.in);
                int num=input.nextInt();
                if(num==1){
                    initial.searchName();
                }else if(num==2){
                    initial.searchNum();
                }
            }catch(InputMismatchException e){
                System.out.println("命令输入错误,请按照提示重新输入数字命令");
            }
        }   
    }
    public void searchName(){
        while(true){
            try{
                System.out.println("输入图书名称");
                Scanner input=new Scanner(System.in);
                String name=input.nextLine();
                for(int i=0;i<books.length;i++){
                    if(books[i].equals(name)){
                        System.out.println("book:"+name);
                        flag=false;
                        break;
                    }
                }
                if(flag){
                    throw new InputMismatchException();
                }
                break;
            }catch(InputMismatchException e){
                System.out.println("图书不存在");
            }
        }
    }
    public void searchNum(){
        while(true){
            try{
                System.out.println("输入图书序号");
                Scanner input=new Scanner(System.in);
                int num=input.nextInt();
                String name=books[num-1];
                System.out.println("book:"+name);
                flag=false;
                break;
            }catch(InputMismatchException e){
                System.out.println("命令输入错误,请按照提示重新输入数字命令");
            }catch(ArrayIndexOutOfBoundsException e){
                System.out.println("图书不存在");
            }
        }
    }
}
2人推荐
随时随地看视频
慕课网APP