*/
面向对象之前-------------------------------------------
*/
import java.util.*;
class Test3
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Book b1=new Book("红高粱","莫言",14);
Book b2=new Book("碧血剑","金庸",84);
Book b3=new Book("小李飞刀","古龙",64);
Book b4=new Book("楚留香","古龙",32);
Book b5=new Book("Thinking in java","tom",100);
List list=new ArrayList();
list.add(b1);
list.add(b2);
list.add(b3);
list.add(b4);
list.add(b5);
System.out.println("请输入要查找的书名:");
String name=sc.nextLine();
Book book=BookTools.findBookByName(name,list);
if(book==null){
System.out.println("查无此书");
}else{
System.out.println(book);
}
}
}
class BookTools
{
//根据书名去查找书籍
public static Book findBookByName(String name,List list){
Book book=null;
for(int i=0;i<list.size();i++){
Book b=(Book)list.get(i);
if(name.trim().equals(b.getBookName().trim())){
book=b;
break;
}
}
return book;
}
}
//首先定义书类
class Book
{
private String bookName;
private String bookAuthor;
private double bookPrice;
public Book(String bookName,String bookAuthor,double bookPrice){
this.bookName=bookName;
this.bookAuthor=bookAuthor;
this.bookPrice=bookPrice;
}
public String getBookName(){
面向对象之后-------------------------------------------
import java.util.*;
class Test4
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
Book b1=new Book("红高粱","莫言",14);
Book b2=new Book("碧血剑","金庸",84);
Book b3=new Book("小李飞刀","古龙",64);
Book b4=new Book("楚留香","古龙",32);
Book b5=new Book("Thinking in java","tom",100);
List list=new ArrayList();
list.add(b1);
list.add(b2);
list.add(b3);
list.add(b4);
list.add(b5);
System.out.println("请输入要查找的书名:");
String name=sc.nextLine();
//定义一个要查找的书籍
Book findBook=new Book(name);
Book book=BookTools.findBookByName(findBook,list);
if(book==null){
System.out.println("查无此书");
}else{
System.out.println(book);
}
}
}
class BookTools
{
//根据书名去查找书籍
public static Book findBookByName(Book findBook,List list){
Book book=null;
if(list.contains(findBook)){ //判断是否包含这本书
int index=list.indexOf(findBook);//得到第一次出现的索引
book=(Book)list.get(index);//根据索引得到这本书
}
/*
上面使用的contains与indexOf方法在内部都默认使用了 Book类的equals方法.
*/
return book;
}
}
//首先定义书类
class Book
{
private String bookName;
private String bookAuthor;
private double bookPrice;
public Book(String bookName,String bookAuthor,double bookPrice){
this.bookName=bookName;
this.bookAuthor=bookAuthor;
this.bookPrice=bookPrice;
}
public Book(String bookName){
this.bookName=bookName;
}
public String getBookName(){