这个系统主要涉及 #面向对象#错误测试。
1.创建图书大类
public class Book {
private String name;
private int num;
public Book(String name,int num){
this.name=name;
this.num=num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
}
2.自定义一个Exception
public class NoExistException extends Exception {
public NoExistException(String message){
super(message);
}
}
3.主程序
import java.util.*;
public class Test {
Book[] book = {new Book("语文",1),
new Book("数学",2),
new Book("外语",3),
new Book("Java编程",4)
};
public List<Book> listbooks;
public Test() {
this.listbooks = new ArrayList<Book>();
}
public void listBooksAdd() {
listbooks.addAll(Arrays.asList(book));
}
public void printBooks() {
System.out.println("---------- 欢迎使用借书系统 ----------");
System.out.println("图书列表展示如下:"); System.out.println("序号" + "\t" + "书名");
for (Book bk : listbooks) {
System.out.println(bk.getNum() + "\t" + bk.getName());
}
}
private Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
Test fb=new Test();
fb.listBooksAdd();
fb.printBooks();
System.out.println();
while(true){
System.out.println("请输入您的命令:1.按名称查找\t2.按序号查找");
switch(fb.wr()){
case 2:
try{
System.out.println("book:"+fb.fbid());
break;
}catch(Exception e){
System.out.println(e.getMessage());
continue;
}
case 1:
try{
System.out.println("book:"+fb.fbbn());
break;
}catch(Exception e){
System.out.println(e.getMessage());
continue;
}
default:
System.out.println("错误,请重新输入");
continue;
}
}
}
public String fbid()throws NoExistException{
System.out.println("请输入书 的序号");
int in=input.nextInt();
for(Book bk : listbooks){
if(in==bk.getNum()){
return book[in-1].getName();
}
}
throw new NoExistException("序号越界,此书籍不存在!!!");
}
public String fbbn()throws NoExistException{
System.out.println("请输入书的名称");
String bname=input.next();
for(Book bk:listbooks){
if(bname.equals(bk.getName())){
return bk.getName();
}
}
throw new NoExistException("名称错误,此书籍不存在!!!");
}
public int wr(){
try{
int in=input.nextInt();
return in;
}catch(Exception e){
return -1;
}
}
}