gpt4 book ai didi

java - 从 ArrayList 中的对象中搜索特定元素

转载 作者:行者123 更新时间:2023-12-02 10:56:19 25 4
gpt4 key购买 nike

这里我创建了一个类:

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>();

我使用 switch case 创建了一个菜单驱动程序

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;
}
}

希望您能从中得到启发。

关于java - 从 ArrayList 中的对象中搜索特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51704702/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com