在这里,我创建了一个类:
class book{
String book_nm;
String author_nm;
String publication;
int price;
book(String book_nm,String author_nm,String publication,int price){
this.book_nm=book_nm;
this.author_nm=author_nm;
this.publication=publication;
this.price=price;
}
}
现在我想根据作者和书名来搜索特定的值
ArrayList<book> bk = new ArrayList<book>();
我使用开关盒创建了一个菜单驱动程序
case 3: System.out.println("Search:"+"\n"+"1.By Book Name\n2.By Author Name");
Scanner s= new Scanner(System.in);
int choice=s.nextInt();
while(choice<3){
switch(choice){
case 1:System.out.println("Enter the name of the book\n");
String name=s.next();
-------
case 2:System.out.println("Enter the name of the author\n");
String name=s.next(); ------
}
}
我知道如何在ArrayList中查找和搜索特定元素,而不是对象。
最佳答案
在ArrayList上使用for循环可以解决您的问题,这是一种幼稚的方法并且过时。
下面是它的代码。
import java.util.ArrayList;
public class HelloWorld{
public static void main(String []args){
String author_name = "abc";
ArrayList<book> bk = new ArrayList<book>();
bk.add(new book("abc", "abc", "abc", 10));
bk.add(new book("mno", "mno", "abc", 10));
bk.add(new book("xyz", "abc", "abc", 10));
ArrayList<book> booksByAuthor = new ArrayList<book>();
for(book obj : bk)
{
if(obj.author_nm == author_name)
{
booksByAuthor.add(obj);
}
}
}
}
class book{
public String book_nm;
public String author_nm;
public String publication;
public int price;
public book(String book_nm,String author_nm,String publication,int price){
this.book_nm=book_nm;
this.author_nm=author_nm;
this.publication=publication;
this.price=price;
}
}
希望您能从中得到启发。