-3

I am doing some validation using simple Java, I am coding as below

if (something.equals("ABC"))

      expectedvalue = "TEST1";

else if(something.equals("DEF"))

      expectedvalue = "TEST5";

// and so on....

My issue here is that, if something.equals("ABC"), expectedvalue can be any of these two values -> "TEST1" or "TEST2"

During validation, in the output, I do not get error if I give "TEST1" for expectedvalue. It should do the same even if I give "TEST2". How to do that?

Kevin Panko
  • 8,356
  • 19
  • 50
  • 61

2 Answers2

2

You have to have a Set of allowed values.

Set<String> allowed = new HashSet<String>();
allowed.put("TEST1");
allowed.put("TEST2");

//and then you can use this set
if (allowed.contains(yourValueToCheck)) {
    // do what you need

Also note that it is safer to compare strings like this:

if ("ABC".equals(something)) // to protect yourself from NullPointerExceptions
Tala
  • 8,888
  • 5
  • 34
  • 38
  • 3
    I tend to stay away from yoda conditions with strings. If my string is null, I want to know about it! – arshajii Aug 02 '13 at 17:39
  • 1
    you will know about it by your app being crashed. The other way to know about it is just check if it is null or not and handle error case yourself without breaking the app – Tala Aug 02 '13 at 17:42
  • A NullPointerException is almost always a sign that something has gone wrong earlier in the program, and that we're no longer in a reliable state. Allowing the exception to be thrown and crash the application earlier gives us the opportunity to fix the real bug. Attempting to hobble along when the application has already failed just gives us the chance to compound the damage. – Ian McLaird Aug 02 '13 at 18:02
  • In many cases I've worked with NULL was a legal value (meaning attribute or some flag wasn't set) – Tala Aug 03 '13 at 06:19
0

Perhaps you could change your test to test with an OR statment?

if(expectedvalue.equals("TEST1") || expectedvalue.equals("TEST2"))
     .....
Xynariz
  • 1,232
  • 1
  • 11
  • 28