gpt4 book ai didi

java - 通过部分用户输入JAVA搜索数组列表

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

我正在尝试使用 JAVA 程序通过用户输入来搜索并打印 ArrayList 值。

用户将输入一个 ID(字符串),我想打印 ArrayList 条目或包含输入的 ID 的条目。 ArrayList 中的所有 ID 全部大写,因此我在下面的代码中使用 .toUpperCase() 。

我目前已经使 ArrayList 只能通过 ID 的完全匹配进行搜索。例如,如果 ID 为“HOUSE”,则用户只能输入完整 ID“house”才能获取返回的 ArrayList 值。

我想添加部分输入的功能以返回数组列表中的值。例如,如果两个 ID 是“HOUSE”和“HOUSTON”,我希望用户能够输入“hou”并获取返回的两个包含“hou”的数组列表值。

我是 JAVA 新手,我在这里进行了很多研究,但仍然无法在这里工作。我将不胜感激任何帮助。这是我为完整 ID 条目编写的代码。

public void find(ArrayList<Plants> pl) {

boolean found = false;
int i = 0;
String inputName = null;

System.out.println("Enter the ID or partial ID of the plant you would like to find: ");
inputName = input.nextLine();

String nameCaps = inputName.toUpperCase();

while(!found && i < pl.size()) {

String id = pl.get(i).getId();

if (id.equals(nameCaps)) {
found = true;
System.out.println(pl.get(i).toString());
}
else {
i ++;
}
}

if (!found) {
System.out.println("A plant with that ID does not exist");
}

} // find end

最佳答案

使用startsWith String 类中的方法。因此,您可以这样做(在找到一个条目后不要打破循环,因为您想打印所有可能的匹配项)

for (int i = 0; i < pl.size(); i++) {
String id = pl.get(i).getId();

if (id.startsWith(nameCaps)) {
found = true;
System.out.println(pl.get(i).toString());
}
}

正如 Aominè@ 的评论中提到的,您可以在此处使用 for-each 循环

for (Plant plant : pl) {
if (plant.getId().startsWith(nameCaps)) {
...
}
}

关于java - 通过部分用户输入JAVA搜索数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50006216/

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