/**
* Created by yuyong on 2017/2/15.
*/
public class Book {
public String bookName;
public int bookNum;
public Book(int bookNum, String bookName) {
this.bookNum = bookNum;
this.bookName = bookName;
}
}
/**
* Created by yuyong on 2017/2/15.
*/
public class NoExistException extends Exception {
public NoExistException(String message) {
super(message);
}
}
import java.util.*;
/**
* Created by yuyong on 2017/2/15.
*/
public class FindBooks {
Book[] book = {new Book(1, "语文"), new Book(2, "数学"), new Book(3, "外语"), new Book(4, "Java编程")};
public List<Book> listbooks;
public FindBooks() {
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.bookNum + "\t" + bk.bookName);
}
}
private Scanner input = new Scanner(System.in);
public static void main(String[] args) {
FindBooks fb = new FindBooks();
fb.listBooksAdd();
fb.printBooks();
System.out.println();
while (true) {
System.out.println("请您输入命令:1.按名称查找书籍\t2.按序号查找书籍");
switch (fb.scanf()) {
case 1:
try {
System.out.println("书籍:" + fb.findByName());
break;
} catch (Exception e) {
System.out.println(e.getMessage());
continue;
}
case 2:
try {
System.out.println("书籍:" + fb.findById());
break;
} catch (Exception e) {
System.out.println(e.getMessage());
continue;
}
default:
System.out.println("错误的命令,请按提示输入,重新输入");
continue;
}
break;
}
fb.input.close();
}
public String findById() throws NoExistException {
System.out.println("请输入书籍的序号:");
int in = input.nextInt();
for (int i = 0; i < book.length; i++) {
if (in == (i + 1))
return book[i].bookName;
}
throw new NoExistException("序号越界,此书籍不存在!!!");
}
public String findByName() throws NoExistException {
System.out.println("请输入书籍的名称:");
String name = input.next();
for (Book bk : listbooks) {
if (name.equals(bk.bookName)) {
return bk.bookName;
}
}
throw new NoExistException("名称错误,此书籍不存在!!!");
}
public int scanf() {
try {
int in = input.nextInt();
return in;
} catch (Exception e) {
input = new Scanner(System.in);
return -1;
}
}
}
---------- 欢迎使用借书系统 ----------
图书列表展示如下:
序号 书名
1 语文
2 数学
3 外语
4 Java编程
请您输入命令:1.按名称查找书籍 2.按序号查找书籍
2
请输入书籍的序号:
5
序号越界,此书籍不存在!!!
请您输入命令:1.按名称查找书籍 2.按序号查找书籍
2
请输入书籍的序号:
4
书籍:Java编程
热门评论
集合类list还没看 所以有点不太理解 到时候回过头来再看看 Mark一下
加油
图解旅途天