-4

I made if statement, but it is so long..

like that :

if("WORDS".equals(object.string1) || "WORDS".equals(object.string2) || "WORDS".equals(object.string3)
|| "WORDS".equals(object.string4) || "WORDS".equals(object.string5) || "WORDS".equals(object.string6)
|| "WORDS".equals(object.string7) || "WORDS".equals(object.string8)  || "WORDS".equals(object.string9)
|| "WORDS".equals(object.string10)) { ......... }

how to make it shorter statement

HealthyRyu
  • 107
  • 1
  • 9
  • 47

2 Answers2

2

Try this

static boolean equalsOr(String a, String... b) {
    for (String s : b)
        if (a.equals(s))
            return true;
    return false;
}

and

if (equalsOr("WORDS", object.string1, object.string2, ...))
1

You could create a function with variable number of arguments:

static bool compareMultiStrings(String words, String ... stringi) {
  if (words == null) return false;

  for(String  s : stringi){
    if (words.equals(s)) return true;
  }

  return false;
}

and then call it from your if:

if (
  compareMultiStrings(
    "WORDS",
    object.string1, object.string2, object.string3, object.string4,
    object.string5, object.string6, object.string7, object.string8,
    object.string9)
)
{ ..... }

The first argument if for your constants string, "WORDS". The other parameters is the varargs parameter.

Jose Luis
  • 994
  • 1
  • 8
  • 22