gpt4 book ai didi

Java swing 搜索数组列表和表单

转载 作者:行者123 更新时间:2023-12-02 05:55:35 24 4
gpt4 key购买 nike

我有一个包含多个人员对象的 ArrayList。我试图要求用户输入employeeID,然后将其显示在表单上。有人可以帮我吗?

findByID = new ActionListener() {
public void actionPerformed(ActionEvent e) {
String question = JOptionPane.showInputDialog("Enter the employees ID: ");
boolean found;
for(Person aPerson: personList) {
if(aPerson.getEmployeeID().equalsIgnoreCase(question)) {
displayDetails(currentItem);
}
else {
System.out.println("This Item doesnt exist");
}
}
}
};

无论输入是什么,我的代码都会重复 else 语句,即使它与我的 ArrayList 中保存的数字匹配。

最佳答案

My code repeats the else statement no matter what the input is even if it matches a number saved in my ArrayList.

当然,因为这就是代码的作用。要仅在未找到某个项目时才执行 else 条件,您需要首先确定是否已找到该项目。现在它会对每个不匹配的项目执行此操作。

所以基本上您需要移动else,使其位于循环之后。

Person foundPerson = null;
for(Person aPerson : personList) {
if(aPerson.getEmployeeID().equalsIgnoreCase(idToLookFor)) {
foundPerson = aPerson;
break;
}
}

if(foundPerson != null) {
/* do something with the person that was found */
} else {
/* did not find the person */
}

关于Java swing 搜索数组列表和表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23121865/

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