Trevor
Trevor

Reputation: 1

Java swing searching arrayList & forms

I have an ArrayList with several person objects. I am trying to ask the user to input the employeeID and then display it on a form. Can anyone help me please?

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

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

Upvotes: 0

Views: 74

Answers (2)

Radiodef
Radiodef

Reputation: 37845

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

Well sure, because that's what the code does. To do the else condition only if an item is not found, you need to decide whether it was found or not first. Right now it does it for every item that's not a match.

So basically you need to move the else so it's after the loop.

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 */
}

Upvotes: 2

clstrfsck
clstrfsck

Reputation: 14829

Not super clear on what you are asking, but you might want something like this:

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

Upvotes: 0

Related Questions