0

I can not figure out where to put equalsIgnoreCase() or toLowerCase() in my code. I'm trying to make it so the search field ignores the case of the users input.

@FXML private void searchForPart(KeyEvent event) {
        if (!partSearch.getText().trim().isEmpty()) {
            partsInventorySearch.clear();
            errorLabel.setText("");
            for (Part p : partsInventory) {
                if (p.getName().contains(partSearch.getText().trim()))
                    partsInventorySearch.add(p);
                else if (Integer.toString(p.getPartID()).contains(partSearch.getText().trim()))
                    partsInventorySearch.add(p);
            }
            if (partsInventorySearch.isEmpty())
                errorLabel.setText("No parts found");
            partTable.setItems(partsInventorySearch);
        }
        else {
            errorLabel.setText("");
            partTable.setItems(partsInventory);
        }
        partTable.refresh();
    }
aweig
  • 9
  • 2

1 Answers1

2

If you need to use contains you should convert both parts of such comparison to the same case.

Also it's better to replace pasting the same code with a single variable:

@FXML
private void searchForPart(KeyEvent event) {
    String search = partSearch.getText().trim().toLowerCase();
    
    if (!search.isEmpty()) {
        partsInventorySearch.clear();
        errorLabel.setText("");
        
        for (Part p : partsInventory) {
            if (p.getName().toLowerCase().contains(search)
               || Integer.toString(p.getPartID()).contains(search)) {
                partsInventorySearch.add(p);
            }
        }
        if (partsInventorySearch.isEmpty())
            errorLabel.setText("No parts found");
        partTable.setItems(partsInventorySearch);
    }
    else {
        errorLabel.setText("");
        partTable.setItems(partsInventory);
    }
    partTable.refresh();
}
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42
  • 1
    Also be careful about localities, you might need to specify a locale for toLowerCase if you want to be independent from the installation environment. Alternatively you can use case insensitive regular expression matches like this: https://stackoverflow.com/a/86832 (But probably the toLower().contains() is faster and easier to understand) – eckes Jan 17 '21 at 00:16