模拟借书系统简易版(慕课网java入门第三季异常)

来源:互联网 发布:老外网络视频教英语 编辑:程序博客网 时间:2024/06/05 17:03
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’,而不是要取的内容。

阅读全文
0 0
原创粉丝点击