Description
构建一个书单类BookList,该类中用一个列表类对象存放书单,提供添加图书(addBook)、查找图书(searchBook)的函数 main函数从键盘输入多个Book添加到书单中,(添加时,提供书的名称、价格、作者、版本号),而后从键盘读入一本书,查找该列表对象中是否包含该书,若包含,输出”found: 该书在列表中的序号”,若不包含,输出“not found”,查找时,提供书的名称、作者、版本号。
Input
添加书的个数 添加的书 查找的书
Output
查找结果
Sample Input
2 ThinkingInJava 86 BruceEckel 4 CoreJava 95 CayS.Horstmann 10 CoreJava CayS.Horstmann 10
Sample Output
found: 1
import java.util.*;
class Book{
private String NameOfBook;
private int price;
private String Author;
private int additionnum;
public Book(String NameOfBook, int price,String Author, int additionnum)
{
this.NameOfBook = NameOfBook;
this.price = price;
this.Author = Author;
this.additionnum = additionnum;
}
public String getName()
{
return this.NameOfBook;
}
public String getAuthor()
{
return this.Author;
}
public int getadditionnum()
{
return this.additionnum;
}
public String toString()
{
return this.NameOfBook;
}
}
class BookList{
LinkedList <Book> booklist ;
public BookList()//一定要初始化!!!!!
{
this.booklist = new LinkedList<>();
}
public void addBook(Book b)
{
booklist.add(b);
}
public void searchBook(Book b)
{
String tempname = b.getName();
int tempaddno = b.getadditionnum();
String tempau = b.getAuthor();
int findflag = 0;
for(int i = 0;i<booklist.size();i++)
{
Book tempbook = booklist.get(i);
if(tempbook.getName().equals(tempname) && tempbook.getadditionnum() == tempaddno && tempbook.getAuthor().equals(tempau))
{
System.out.println("found: "+i);
findflag = 1;
}
}
if(findflag == 0)
{
System.out.println("not found");
}
}
}
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
BookList bl = new BookList();
int n = s.nextInt();
for (int i=0; i<n;i++) {
bl.addBook(new Book(s.next(),
s.nextInt(),
s.next(),
s.nextInt()));
}
bl.searchBook(new Book(s.next(),
0,
s.next(),s.nextInt()));
}
}
版权声明:本文为Yolanda_Salvatore原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。