3

I want to pass one of four operators (+, -, *, /) to a method, and have it perform an operation on two integers based on which operator was passed.

static int op(String oper) {
    eval = 8 oper 4;
}

e.g. if I call it with op("+");, it'll add 8 and 4.

Right now, I just get a "; expected" after 8.

Is there some other syntax I should use? I'm just trying to cut down the size of some code.

syb0rg
  • 8,057
  • 9
  • 41
  • 81
Adam
  • 355
  • 1
  • 6
  • 12
  • we can only dream that such code can work (in java) – irreputable Feb 27 '13 at 02:42
  • java is not an interpreted language. You are telling the compiler : eval = 8 "+" 4. That is not correct syntax. You could pass in a operator and then use a swtich statement to perform the "real" operation as needed. – OldProgrammer Feb 27 '13 at 02:44
  • @LeorA - no hes not, hes telling the compiler, literally, `8 oper 4`. Like you said, Java is not an interpreted language, and it does not perform variable expansion on language tokens. In any case, the code as written by the OP is uncompilable. – Perception Feb 27 '13 at 02:47
  • If you really need to evaluate that way, try [this method][1]. [1]: http://stackoverflow.com/questions/3422673/evaluating-a-math-expression-given-in-string-form – jarmod Feb 27 '13 at 02:48

1 Answers1

5

In Java 8, we'll be able to do something like

foo(IntBinaryOperator oper) 

    eval = oper.apply(8, 4);

then

foo(Integer::sum);

IntBinaryOperator times = (a,b)->a*b;
foo(times);

foo( (a,b)->a/b );
irreputable
  • 44,725
  • 9
  • 65
  • 93