evaluate boolean values in Java - java

I am trying to evaluate the following from a string
boolean value = evaluate("false || true && true && false || true");
I need to get a boolean value of true for this one.
Any ideas on how to solve this problem in the most efficient way?

String value = ("false || true && true && false || true");
boolean result = false;
for (String conj : value.split("\\|\\|")) {
boolean b = true;
for (String litteral : conj.split("&&"))
b &= Boolean.parseBoolean(litteral.trim());
result |= b;
}
System.out.println(result); // prints true

If the only operators are && and ||, then I think this will work:
static boolean eval(String str) {
String s = str.replaceAll("\\s|\\|\\|false|false\\|\\|", "");
return !s.contains("false") || s.contains("||true");
}
For more complicated expressions, I found this library just for that.
Don't know how efficient it is though.

You'll need a small boolean expressions grammar. A bit of recursive parsing should do the trick.
If you don't know how to write such a parser, you may use JavaCC or something similar.

there are parsergenerators available for which you can define a grammar.
But if you only got || and && as operators and true and false as values you can easily do this by yourself, by implmenting a very simple finite state machine:
1.) Split the string into the tokens
2.) parse the left most value by using Boolean.parseBoolean(token) and safe it's value in some instance variable (your state)
3.) combine your instance variable with the next boolean token using the given operator
4.) Repeat step3 until you finished through the whole string
This seems to work although i havent thorougly tested it :)
public class BooleanFSParser {
private boolean parse(String data) {
String[] tokens=data.split("\\s");
boolean state=Boolean.parseBoolean(tokens[0]);
for (int i=1;i<(tokens.length / 2) + 1;i=i+2){
if (tokens[i].equals("&&")){
state=state && Boolean.parseBoolean(tokens[i+1]);
}else{
state=state || Boolean.parseBoolean(tokens[i+1]);
}
}
return state;
}
public static void main(String[] args) {
BooleanFSParser parser = new BooleanFSParser();
boolean val = parser.parse("true && true || false");
System.out.println(String.valueOf(val));
}
}
thats should give you a cirrectly parsed value, but it will get a bit more complex if you allow brackets for example ;)
have fun and check here for the theory
Finite-state_machine

Related

Reducing conditional operators efficiently

What I am trying to perform: I am trying to reduce the conditional operators, Since Sonar is giving a error for it
if (!parseBooleanFromString(response.getBuy().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getSell().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getExchange().getHasEligibleAccounts()) &&
(!parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()) &&
(!parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeInvestments())))))) {
//Success
} else {
//Failure
}
private boolean parseBooleanFromString(String mStr) {
return Boolean.parseBoolean(mStr);
}
What i have tried:
I am trying to put all the boolean values in a list and check
Is that the best way to do or is there a more efficient way
You can also move these conditions into different functions which internally calls other functions and returns single boolean result. This way there will only one function in above if condition which will internally evaluate and returns result.
Since you're checking if each statement is false, how about you keep a global integer in memory: private int product = 1;. Make a separate method where you calculate the product (replaces the string to boolean parser):
private void updateProduct(String mStr){
if (Boolean.parseBoolean(mStr)) //If true, condition should fail
product *= 0;
else
product *= 1;
}
In essence, you are not running 'if statement' but multiplying the boolean:
product = 1;
updateProduct(response.getBuy().getHasEligibleAccounts());
updateProduct(response.getSell().getHasEligibleAccounts());
//etc
if (product > 0){
//success
} else {
//failure
}
Explanation: If at any point a condition was true, the product will always be 0. The only instance where the product is > 0 is when all statements were false
Not sure what sonar complains about, but you have alot of redundant parenthesis and confusing negations. Using DeMorgans law, you can at least simplify to:
boolean b = parseBooleanFromString(response.getBuy().getHasEligibleAccounts())
|| parseBooleanFromString(response.getSell().getHasEligibleAccounts())
|| parseBooleanFromString(response.getExchange().getHasEligibleAccounts())
|| parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions())
|| parseBooleanFromString(
response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions());
if (!b) {
or if you perfer more java 8 syntax
Stream<Boolean> bools = Stream.of(parseBooleanFromString(response.getBuy().getHasEligibleAccounts()),
parseBooleanFromString(response.getSell().getHasEligibleAccounts()),
parseBooleanFromString(response.getExchange().getHasEligibleAccounts()),
parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()),
parseBooleanFromString(response.getWorkplaceRetirement().getHasPlansEligibleForChangeContributions()));
boolean c = ! bools.anyMatch(e -> e);
if (!c) {
I would do something like this:
private boolean checkEligibility(LaunchPoints response) {
final String trueStr = "true";
if (trueStr.equals(response.getBuy().getHasEligibleAccounts())) return true;
if (trueStr.equals(response.getSell().getHasEligibleAccounts())) return true;
[...]
return false;
}
The idea is, skip the parsing boolean, just check for "true" and make your conditions more readable.

Return boolean from method that calls an Int

As per instructions: Write a static method that takes one integer as a formal parameter and returns a Boolean value of True if the parameter value is even and False if the it odd. It would seem my method must call an int instead of a boolean. With that being said I don't know how to return a boolean from a method that calls an int. I've tried this but it doesn't work.
EDIT - Language is JAVA.
\nEDIT 2 - For anyone looking at this in the future, I originally meant to type private static int result. Not private static boolean result. That mistake ended up fixing my code.
}
private static boolean result(int userIn)
{
if (userIn % 2 == 0)
{
int yes = 1;
return true;
}
else
{
return false;
}
}
Your original question didn't actually specify programming language, and it's not clear why you think you need to "call an int".
However in most C-descendent languages, and keeping with the style of your code quote, the following should work
private static boolean result(int userIn)
{
return (userIn % 2) == 0;
}
The expression (userIn % 2) == 0 will evaluate to a boolean (or your language's representation of one).
It is a common anti-idiom for people learning to program to do something like:
if (some condition is true)
then
return TRUE
else
return FALSE
Most (modern) programming languages allow you to simply return the result of evaluating a boolean condition, or to assign it to a suitably typed variable.
Thus
boolean result = (myvariable >= 10)
has the same result as, but is much more readable than:
boolean result
if (myvariable >= 10)
result = TRUE
else
result = FALSE
This may be what the person who set the assignment is wanting you to learn from it.

Simplify Boolean Expression example

how to simplify
if ( this.something == false )
this boolean expression ?
Actually I want to ask is what is Simplify Boolean Expression?
You can simply do:
if (!this.something)
You can use boolean variables directly:
Example:
boolean flag = true;
if(flag) {
//do something
}
Use like following since if expression need a boolean value.
if (!this.something) {
//
}
You can use ternary operator for more simplification :
int someVariable = (this.something) ? 0:1;
someVariable will be 1 if this.something is false.
Hope this helps.
To simplify boolean expression is to reduce complexity of this expression, with preserving the meaning.
In your case:
if(!this.something)
has the same meaning but it's a little bit shorter.
To simplify more complex examples you can use truth tables or Karnaugh maps.
Generally the if statement wants to evaluate whatever is within it into a boolean
if
boolean something = true;
if(something == true) evaluates to true
if(something != true) evaluates to false
but you can also do
if(something) evaluates to whatever something is (true in this case)
if(!something) evaluates to opposite what something is (false in this example)
Also you can simplify if statements in certain cases by using a ternary operator:
boolean isSomethingTrue = (something == true) ? true : false;
boolean isSomethingTrue = something ? true : false;
type variable = (condition) ? return this value if condition met : return this value if condition is not met;

Do I have this written properly? .equals AND !.equals if statement

FIXED. To get the statement to evaluate the way I wanted it to I had to write it this way:
public static Boolean pushCard(String S1, String S2) {
Boolean result = false;
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") && (!S2.equals("water") && (!S2.equals("fire"))))
result = true;
return result;
} //end push card method
I can not tell if this comparison is causing issues. I was using == instead of .equals but then I learned that it was the wrong way to write it. Thanks for the help!
public static Boolean pushCard(String S1, String S2) {
Boolean result = false;
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") || (!S2.equals("water") || (!S2.equals("fire"))))
result = true;
return result;
} //end push card method
Syntactically, your code will compile just fine, and the way you use .equals() method to compare strings is correct. Your use of the ! operator is also correct.
There is no guarantee that your code will not have logical errors though.
The only problem I can see you have "fire" mentioned twice in your second if statement. Otherwise, any problems you might be having could be related to your logic being wrong, since your syntax is pretty much correct and your usage is proper.
It is unclear what you're asking. The second if will always be true. You probably need :
if ((S1.equals("fire") || S1.equals("wind") || S1.equals("water")))
if (!S2.equals("fire") && (!S2.equals("water") && (!S2.equals("wind"))))
result = true;
public static Boolean pushCard(String S1, String S2)
{
Boolean result = false;
if (S1.equals("fire") || S1.equals("wind") || S1.equals("water"))
{
(!S2.equals("fire") || !S2.equals("water"))
result = true;
}
return result;
}
/end push card method
you had an extra pair of brackets in the first if statement.
I believe an if statement needs brackets {} when the code inside it is larger than one line.
your second if statement can be altered to just !S2.equals("fire") || !S2.equals("water")

Cleanest way to toggle a boolean variable in Java?

Is there a better way to negate a boolean in Java than a simple if-else?
if (theBoolean) {
theBoolean = false;
} else {
theBoolean = true;
}
theBoolean = !theBoolean;
theBoolean ^= true;
Fewer keystrokes if your variable is longer than four letters
Edit: code tends to return useful results when used as Google search terms. The code above doesn't. For those who need it, it's bitwise XOR as described here.
There are several
The "obvious" way (for most people)
theBoolean = !theBoolean;
The "shortest" way (most of the time)
theBoolean ^= true;
The "most visual" way (most uncertainly)
theBoolean = theBoolean ? false : true;
Extra: Toggle and use in a method call
theMethod( theBoolean ^= true );
Since the assignment operator always returns what has been assigned, this will toggle the value via the bitwise operator, and then return the newly assigned value to be used in the method call.
This answer came up when searching for "java invert boolean function". The example below will prevent certain static analysis tools from failing builds due to branching logic. This is useful if you need to invert a boolean and haven't built out comprehensive unit tests ;)
Boolean.valueOf(aBool).equals(false)
or alternatively:
Boolean.FALSE.equals(aBool)
or
Boolean.FALSE::equals
If you use Boolean NULL values and consider them false, try this:
static public boolean toggle(Boolean aBoolean) {
if (aBoolean == null) return true;
else return !aBoolean;
}
If you are not handing Boolean NULL values, try this:
static public boolean toggle(boolean aBoolean) {
return !aBoolean;
}
These are the cleanest because they show the intent in the method signature, are easier to read compared to the ! operator, and can be easily debugged.
Usage
boolean bTrue = true
boolean bFalse = false
boolean bNull = null
toggle(bTrue) // == false
toggle(bFalse) // == true
toggle(bNull) // == true
Of course, if you use Groovy or a language that allows extension methods, you can register an extension and simply do:
Boolean b = false
b = b.toggle() // == true
The class BooleanUtils supportes the negation of a boolean. You find this class in commons-lang:commons-lang
BooleanUtils.negate(theBoolean)
Boolean original = null; // = Boolean.FALSE; // = Boolean.TRUE;
Boolean inverse = original == null ? null : !original;
If you're not doing anything particularly professional you can always use a Util class. Ex, a util class from a project for a class.
public class Util {
public Util() {}
public boolean flip(boolean bool) { return !bool; }
public void sop(String str) { System.out.println(str); }
}
then just create a Util object
Util u = new Util();
and have something for the return System.out.println( u.flip(bool) );
If you're gonna end up using the same thing over and over, use a method, and especially if it's across projects, make a Util class. Dunno what the industry standard is however. (Experienced programmers feel free to correct me)
Before:
boolean result = isresult();
if (result) {
result = false;
} else {
result = true;
}
After:
boolean result = isresult();
result ^= true;

Categories