Right now I'm going to have to write a method that looks like this:
public String Calculate(String operator, double operand1, double operand2)
{
if (operator.equals("+"))
{
return String.valueOf(operand1 + operand2);
}
else if (operator.equals("-"))
{
return String.valueOf(operand1 - operand2);
}
else if (operator.equals("*"))
{
return String.valueOf(operand1 * operand2);
}
else
{
return "error...";
}
}
It would be nice if I could write the code more like this:
public String Calculate(String Operator, Double Operand1, Double Operand2)
{
return String.valueOf(Operand1 Operator Operand2);
}
So Operator would replace the Arithmetic Operators (+, -, *, /...)
Does anyone know if something like this is possible in java?
Method arguments in Java must be expressions. An operator by itself is not an expression. This is not possible in Java.
You can, of course, pass objects (maybe
enum
constants) that represents those operators, and act accordingly, but you can't pass the operators themselves as parameters.Additional tips
Since you're just starting Java, it's best to ingrain these informations early on to ease your future development.
calculate
instead ofCalculate
operator
instead ofOperator
Double
is a reference type, the box for primitive typedouble
.return "error..."
. Instead,throw new IllegalArgumentException("Invalid operator");
See also
No this is not possible in this way.
You will need a parser to do what you want, and this can be cumbersome.
You're probably asking the wrong question, since you are getting the wrong answer.
If you are looking for a mathematical parser you might want to take a look at this project on SF: http://sourceforge.net/projects/jep/
There might be some answers in this.
You can't pass operators directly. You could use functors.
No, you can't do that in Java. The compiler needs to know what your operator is doing. What you could do instead is an enum:
You can then write a method like this:
And call it like this:
There's only the cumbersome way of doing it with a callback interface. Something like
Then you implement the operators you need:
And your generic method takes an Operator and the two arguments:
You could also use an enum instead of an interface if you only need a smaller, fixed number of operators.
You can either
Use a functional language for JVM to implement this part of your code (clojure, scala et el), wrap lambda functions around math operators and pass those functions as parameters
Get an expression evaluator for Java like http://www.singularsys.com/jep/ (and there must be many free alternatives as well)