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?
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: