0

this below is the code :

public String evaluate() {

    if (this.data.equals("+")) {
      return String.valueOf(Double.parseDouble(this.children.get(0).evaluate()) + Double.parseDouble(this.children.get(1).evaluate()));
    } 

else if (this.data.equals("-")) {
      return String.valueOf(Double.parseDouble(this.children.get(0).evaluate()) - Double.parseDouble(this.children.get(1).evaluate()));
    } 

else if (this.data.equals("*")) {
      return String.valueOf(Double.parseDouble(this.children.get(0).evaluate()) * Double.parseDouble(this.children.get(1).evaluate()));
    } 

else {
      return String.valueOf(Double.parseDouble(this.children.get(0).evaluate()) / Double.parseDouble(this.children.get(1).evaluate()));
    }

  } 

the this.data value hold's the operand in form of String. Is there a way to eliminate the if-else altogether, decrease the lines of the code.? No to using switch case also.

Is there a way to convert string to operand in java.?

  • You could use a factory method that from `"+"` instantiates a class `Plus` that represents the plus operator, etc. But it will still need to have `if` conditions or `switch-case` to decide which class to instantiate. – jbx Oct 26 '19 at 16:48
  • @jbx the whole idea is to avoid switch or if-else. – need2learnJAVA Oct 26 '19 at 16:51
  • Short answer: No. See [Is it possible to pass arithmetic operators to a method in java?](https://stackoverflow.com/questions/2902458/is-it-possible-to-pass-arithmetic-operators-to-a-method-in-java) for more information. – Tim Biegeleisen Oct 26 '19 at 16:55
  • @NeeharikaKompala yes I understood your whole idea. But it is very difficult to achieve it in the way you are thinking. Java doesn't treat strings as evaluatable expressions (unlike Javascript which has the `eval()` function). – jbx Oct 26 '19 at 16:56
  • Possible duplicate of [How to evaluate a math expression given in string form?](https://stackoverflow.com/questions/3422673/how-to-evaluate-a-math-expression-given-in-string-form) – jbx Oct 26 '19 at 16:57

2 Answers2

2

There is a pretty elegant way to implement this behavior by using an enum. Since java enums aren't just enumerations (like in other programming languages) but either full classes you can write this enum (simple example for '+' and '*'):

public enum Operation {
 PLUS("+") {
            @Override
            public int apply(int value1, int value2) {
                return value1 + value2;
            }
        },
MULTIPLY("*") {
            @Override
            public int apply(int value1, int value2) {
                return value1 * value2;
            }
};

private final String symbol;

private static final Map<String, Operation> STRING_TO_ENUM = Arrays.stream(Operation.values()).collect(Collectors.toMap(Operation::toString, e -> e));

private Operation(String symbol) {
     this.symbol = symbol;
}

public static Operation fromString(String symbol) {
    return STRING_TO_ENUM.get(symbol);
}

@Override
public String toString() {
    return symbol;
}

public abstract int apply(int value1, int value2);
}

and reduce the evaluation to:

public evaluate() {
    return Operation.fromString(this.data).apply(value1, value2);
} 
Mobold
  • 595
  • 3
  • 8
1

This question was asked several times before, and as far as I can tell from reading the answers (and my own experience with java), there is no java-native function (like expression.eval()) that will do your job. The main reason for this may be that java can never know where the expressions/values come from, and therefor cannot deliver an overall solution that satisfies e.g. both input validation and completeness etc.

However (!), as usual smart people sat down and coded their own solutions. You may find this or that SO Question/Answers usefull. The answers list several solutions to your problem.

Depending on your usecase, you may not want to overcomplicate things. E.g, if you only want to evaluate the four operands/expression-types you included above, you could simply 'outsource' your code to its own library, and thereby keep your main class clean without dealing with 3rd-party code.

I know, this is not the answer you were hoping for. Consider this a chance to deepen your understanding and knowledge of the language.

Obviously, cou could as well transfer your logic to a language that supports the evaluation of string expressions.

Happy coding

randmin
  • 818
  • 8
  • 16