模擬借書系統簡易版(慕課網java入門第三季異常)

package com.imooc.book;

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

public class Book {
    String bName;
    int bNum;
    public static   Book[]bookList = new Book[5];

    public Book(){

    }
    public Book(String name,int num){
        bName = name;
        bNum = num;

    }
    public void FindByName(String name){
        for(int i=0;i<bookList.length;i++){
            if(bookList[i].bName.equals(name)){
            System.out.println("book:"+name);
            return;
        }
        }
        System.out.println("圖書不存在");

    }
    public void FindByNum(int num){
        for(int i=0;i<bookList.length;i++){
            if(bookList[i].bNum==num){
                System.out.println("book"+bookList[i].bName);
                return;

            }
        }
        System.out.println("圖書不存在");
    }

    public static void main(String[]args){
        Book book = new Book();
        Book.bookList[0]=new Book("高數",1);
        Book.bookList[1]=new Book("大物",2);
        Book.bookList[2]= new Book("線代",3);
        Book.bookList[3]=new Book("英語",4);
        Book.bookList[4]=new Book("化學",5);

        while(true){
            System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
            Scanner scan = new Scanner(System.in);
            try{
                int cmd = scan.nextInt();
                scan.nextLine();
                switch(cmd){
                    case 1:
                            System.out.println("輸入圖書名稱:");
                            String name = scan.nextLine();
                            book.FindByName(name);
                            scan.close();
                            break;

                    case 2:
                        System.out.println("輸入圖書序號:");
                        int num = scan.nextInt();
                        scan.nextLine();
                        book.FindByNum(num);
                        scan.close();
                        break;

                    default:
                        System.out.println("命令輸入錯誤!請根據提示輸入數字命令!");

                }   
            }catch(InputMismatchException e){
            //e.printStackTrace();
            System.out.println("命令輸入錯誤!請根據提示輸入數字命令!");
            }
        }
    }
}

注意Scanner類的nextInt函數,只會取走數字,不會取走‘\r’導致下一次next()函數得到的是‘\r’,而不是要取的內容。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章