我正在尝试以 ArrayList 的形式创建一个注册表,它将保存我读过的各种书籍。 该计划只有两个类(class)。一个作为条目的模板(名称:Entry),另一个管理 ArrayList 中的条目(名称:Registry)。
这些是 Entry 的属性:
private final String title;
private final String mangaka;
private final String year;
private final String genre;
private final String volumes;
private String completelyScanlated;
private String licensedInGerman;
private String read;
private String comments;
因此有这个构造函数:
public Entry(final String title, final String mangaka, final String year, final String genre, final String volumes,
String completelyScanlated, String licencedInGerman, String read, String comment)
{
this.title = title;
this.mangaka = mangaka;
this.year = year;
this.genre = genre;
this.volumes = volumes;
this.completelyScanlated = completelyScanlated;
this.licensedInGerman = licensedInGerman;
this.read = read;
this.comments = comments;
}
“Registry”类只有一个属性:
ArrayList<Entry> entries = new ArrayList<Entry>();
用户通过在控制台中输入字符串来通过“扫描仪”创建一个条目。创建的对象通过以下方式保存在ArrayList中:
Entry object = new Entry(title, mangaka, year, genre, volumes, completelyScanlated, licensedInGerman, read, comments);
entries.add(object);
现在我想检查一个字符串(也是使用控制台输入创建的)是否等于属性“title”。我可以使用方法“.contains()”检查输入的相等性,但此方法会比较所有属性。有没有办法只检查一个属性?
这是不起作用的代码:
public void findEntry()
{
Scanner input = new Scanner(System.in);
System.out.println("Which title do you want to search for?");
String searchedEntry = input.nextLine();
System.out.println();
if (entries.contains(searchedEntry)) {
int x = entries.indexOf(searchedEntry);
entries.get(x);
//Entry.showDetails();
}
}
结果是通过控制台给出的(尽管该代码正在运行)。
提前致谢
最佳答案
我假设您的 Entry 类中有一个 Title 的 setter/getter 。类似于 getTitle() 之类的东西。然后迭代所有条目并检查其标题是否包含搜索字符串。
public void findEntry(){
Scanner input = new Scanner(System.in);
System.out.println("Which title do you want to search for?");
String searchedEntry = input.nextLine();
System.out.println();
for(Entry entry : entries){
if(entry.getTitle().contains(input))
entry.showDetails(); // or Whatever
}
}
最好将标题和搜索字符串转换为小写。
if(entry.getTitle().toLowerCase().contains(input.toLowerCase()))
所以你可以搜索“指环王”,会找到“指环王:护戒使者”。
关于java - 如何检查 ArrayList 中某个条目的字符串与一个字符串属性(众多)的相等性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34200364/