Complex if () or enum?

In my application, I need to fork out if the input matches some specific 20 elements.

I was thinking about using an enumeration

public enum dateRule { is_on, is_not_on, is_before,...}

and enum constant switch to execute function

switch(dateRule.valueOf(input))
{
  case is_on : 
  case is_not_on :
  case is_before :
  .
  .
  .
  // function()
  break;
}

But the input lines will look like "on on", "not included", "before", etc. without _ between words. I found out that an enumeration cannot contain constants containing space.

Possible ways I could figure out:

1, using an if statement to compare 20 possible inputs that give a long if statement, for example

if(input.equals("is on") ||
   input.equals("is not on") || 
   input.equals("is before") ...)   { // function() }

2, Work on the input to insert _ between words, but even with other input lines that do not fall under this 20, can have several words.

Is there a better way to implement this?

+5
source share
5

. .

, , .

, 20

, -. , - .

, : , , , .. 20

public enum dateRules
{
   is_on
   ,is_not_on
   ,is_before
   ,is_after
   .
   .
   .
}

if(isARule(in = input.replace(" ","_"))
{
   switch(dateRule.valueOf(in))
   {
      case is_on,
      case is_not_on,
      case is_before, ...
   }
}

"input" "in", "_" ".".

private static boolean isARule(String value)
  {
    for(dateRule rule : dateRule.values())
    {
      if(rule.toString().equals(value))
      {
        return true;
      }
    }
    return false;
  }

.

: fooobar.com/questions/64578/...

0

. - :

public enum MyEnumType
{
    IS_BEFORE("is before"),
    IS_ON("is on"),
    IS_NOT_ON("is not on")

    public final String value;

    MyEnumType(final String value)
    {
        this.value = value;
    }
}

enum ( ), :

public boolean isOnOrNotOn()
{
    return (this.value.contentEquals(IS_ON) || this.value.contentEquals(IS_NOT_ON));
}

:

switch(dateRule.valueOf(input))
{
    case IS_ON: ...
    case IS_NOT_ON: ...
    case IS_BEFORE: ...
}

IS_ON, , System.out.println(IS_ON), is on.

+3

valueOf ( valueOf).

public enum State {
    IS_ON,
    IS_OFF;

    public static State translate(String value) {
        return valueOf(value.toUpperCase().replace(' ', '_'));
    }
}

, .

State state = State.translate("is on");

switch .

+3

Java 7, switch :

switch (input) {
    case "is on":
        // do stuff
        break;
    case "is not on":
        // etc
}
+1

, ...

"is", , ,

"", , !

, , .

So, divide between spaces. Parse the separated words to make sure they exist in the syntax definition, and then perform a step-by-step evaluation of the passed expression. This will allow you to easily expand the syntax (without the need to add "is" and "is not" for each combination, and read the code easily.

Having several conditions associated with one for the purpose of switch statements leads to huge bloating over time.

0
source

All Articles