Java 借书系统(控制台)
借书系统(控制台)
- 输入命令类型错误,抛出命令错误异常,并提示重新输入
- 输入命令不存在,抛出命令错误异常,并提示重新输入
- 输入书名不存在,抛出异常,并提示重新输入
- 输入序号类型错误,抛出序号不正确异常,并提示重新输入
- 输入序号越界,抛出序号越界异常,并提示重新输入
FindBook.java
package com.xk;
import java.util.Scanner;
public class FindBook {
Scanner input=new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
String books[]= new String[]{"语文","数学","英语","Java","Android"};
System.out.println("-----------欢迎使用我的借书系统-----------");
FindBook fb=new FindBook();
while(true) {
System.out.println("请您输入命令:1.按名称查找书籍\t2.按序号查找书籍");
switch(fb.scanf()) {
case 1:
try {
System.out.println("book:"+fb.byName(books));
break;
}catch(Exception e){
System.out.println(e.getMessage());
continue;
}
case 2:
try {
System.out.println("book:"+fb.byId(books));
break;
}catch(Exception e){
System.out.println(e.getMessage());
continue;
}
default : System.out.println("错误命令请按提示输入,请重新输入:");continue;
}
break;
}
fb.input.close();
}
public int scanf(){
try{
int in=input.nextInt();
return in;
}catch(Exception e){
input=new Scanner(System.in);
return -1;
}
}
public String byName(String books[])throws Exception{
System.out.println("请输入图书名称:");
String name=input.next();
for(int i=0;i<books.length;i++){
if(name.equals(books[i])){
return books[i];
}
}
throw new Exception("图书不存在!");
}
public String byId(String books[])throws Exception{
System.out.println("请输入图书序号:");
FindBook fb=new FindBook();
int flag=fb.scanf();
if(flag==-1) {
throw new Exception("输入序号不正确");
}
try {
return books[flag];
}catch(ArrayIndexOutOfBoundsException e){
throw new ArrayIndexOutOfBoundsException("输入序号越界");
}
}
}
运行效果:
相关文章