This question already has an answer here:
- Evaluate String as a condition Java 8 answers
I am learning Java now and don't know how to convert an input string(such as "4>1"
) to get a boolean return.
The goal that I want to achieve is that, let Java return boolean
(true/false) based on the user input, which is in String
?
For example, I tried to get a return value of "true
" for input "!(4>=10)
".
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 aString
with value"true"
or"false"
to aBoolean
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:
Then, what you could do, is split your string in 3 parts using a regular expression.
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.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)Suye Shen, in Java strings are not expressions - they are just a series of characters, and if you ask what the boolean value of them they will always be false (to say, any string has no boolean value).
You can turn a string into an expression that can have a boolean value - you just need to create a parser to read the contents of the string - and a resolver, to evaluate the parsed symbols into a boolean value.
Making a parser and a resolver is not very hard, but it's worth noting that it can change dramatically if you add more math into the problem. The way you wrote your problem, you just want to evaluate expressions like:
So basically, you just want to support the symbols {!, <=, >=, <, >}. Not even "+", "-" or "=" are required. and you only want to use Integers (whole numbers) as the arguments. That makes it simple. I even removed the "(" and ")" to make it the simplest of examples.
The result of running this may be like:
I hope you can take this basic example and expand on it to include more math like {+,-,=,/,*,(,)} and more symbols, as well as non integer numbers. There are libraries for parsing and resolving out there that may be used, but tackling this issue on your own could be a good Java lesson.