0

I'm trying to accept a user field in the form of a jTextArea (Search box). Then take this text and compare it against an ID OR Name and return if its inside of any.

  • Compare User Entry to ID
  • Compare User Entry to Name

Essentially check the user entry against a String and an Int.

I've got the following however am getting NumberFormatException.

String name = "Window";
int id = 12;
if (name.contains(searchText.getText().toLowerCase()) || id == Integer.valueOf(searchText.getText().replaceAll("[^0-9]", ""))) {
                    // TRUE STATEMENT
                }

So if a user enters "Win" it will return true. If they enter "test" it will return false. However if they enter "1","2" or "12" it will return true since the ID contains these.

I think I'm overthinking this one and could use some help. Thanks in advance

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • So when you enter some `text` that is **not** `Win` and is not **not** a number it will fail. – Scary Wombat Sep 30 '19 at 00:40
  • @ScaryWombat - If you enter a number that's NOT the ID. – DotSlashShell Sep 30 '19 at 00:41
  • No, why are you even trying to convert to a Number. `"12"` is a String. If you entered `Fred` then the first part fails then it tries to convert to a Number which it is **NOT** – Scary Wombat Sep 30 '19 at 00:42
  • Sorry - Just edited the question. It's actually an int – DotSlashShell Sep 30 '19 at 00:42
  • 2
    Have a look at this question https://stackoverflow.com/questions/1102891/how-to-check-if-a-string-is-numeric-in-java – Scary Wombat Sep 30 '19 at 00:43
  • @ScaryWombat Thanks for the link. Using that plus some editing for my code above it worked! You rock! – DotSlashShell Sep 30 '19 at 01:04
  • As a general tip, it's best to avoid doing things like `if (name.toLowerCase().contains(searchText.getText().toLowerCase())) { ... }` – the more code you write, you will encounter things like `name` is null, or `searchText` is null, or `getText()` is null, or who know what else happens and you'll get an exception with a stacktrace that points at that _line_ of code and you won't be able to figure out what the problem was. Use variables, break things into smaller statements. It will save you sanity down the road. – Kaan Sep 30 '19 at 01:07
  • @kaan Good call. Worth mentioning that Apache StringUtils has a null-safe `containsIgnoreCase` - https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html#containsIgnoreCase-java.lang.CharSequence-java.lang.CharSequence- – racraman Sep 30 '19 at 01:13

1 Answers1

2
 if (name.toLowerCase().contains(searchText.getText()) 
                    || Integer.toString(id).contains(searchText.getText())) {
                System.out.println("TRUE");
             }
upog
  • 4,965
  • 8
  • 42
  • 81