There is no easy answer
For starters there are no easy solutions. I noticed somebody mentioning Boolean.valueOf(...)
;
The goal of the Boolean.valueOf(String)
method is not to evaluate conditions or equations. It is just a simple method to convert a String
with value "true"
or "false"
to a Boolean
object.
Anyway, if you want this kind of functionality, you have to set some clear limitations. (note: some equations have no answer: “0/0 = 0/0”)
Regex parsing
If you are simply comparing integers with integers, then you could assume that the equations will always be in the following format:
<integer1>[whitespace]<operator>[whitespace]<integer2>
Then, what you could do, is split your string in 3 parts using a regular expression.
public static boolean evaluate(String input)
{
Pattern compile = Pattern.compile("(\\d+)\\s*([<>=]+)\\s*(\\d+)");
Matcher matcher = compile.matcher(input);
if (matcher.matches())
{
String leftPart = matcher.group(1);
String operatorPart = matcher.group(2);
String rightPart = matcher.group(3);
int i1 = Integer.parseInt(leftPart);
int i2 = Integer.parseInt(rightPart);
if (operatorPart.equals("<")) return i1 < i2;
if (operatorPart.equals(">")) return i1 > i2;
if (operatorPart.equals("=")) return i1 == i2;
if (operatorPart.equals("<=")) return i1 <= i2;
if (operatorPart.equals(">=")) return i1 >= i2;
throw new IllegalArgumentException("invalid operator '" + operatorPart + "'");
}
throw new IllegalArgumentException("invalid format");
}
Script Engines
Java also supports script engines (e.g. Nashorn and others). These engines can call javascript methods, such as the eval(...)
javascript method, which is exactly what you need. So, this is probably a better solution.
public static boolean evaluate(String input)
{
try
{
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
Object result = engine.eval("eval('" + input + "');");
return Boolean.TRUE.equals(result);
}
catch (ScriptException e)
{
throw new IllegalArgumentException("invalid format");
}
}
This solution can handle more complicated input, such as "!(4>=10)"
.
Note: for security reasons, you may want to strip specific characters from the user input. (e.g. the '
character)
solved how to parse an input string such as “4>1”, resolve the expression and return boolean [duplicate]