Using string input as boolean - java

String input = sc.nextLine();
System.out.println(Boolean.parseBoolean(input));
So my inputs look like 1 > 2 or false || true, but I'm not getting the correct values.
But when I call:
Boolean x = 1 < 2;
System.out.println(x);
I get them correct. So my question is. How do I convert String input to return boolean value?
So far tried:
Boolean.parseBoolean();
Boolean.getBoolean();
Boolean.valueOf();
Thanks for your answers.
EDIT
INPUT - OUTPUT
1 < 2 - false(should be true)
false || true - false(should be true)

You can use ScriptEngine for this:
ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
String input = "1 > 2";
System.out.println(engine.eval(input)); //prints false

Boolean.parseBoolean(String) is implemented as:
public static boolean parseBoolean(String s) {
return ((s != null) && s.equalsIgnoreCase("true"));
}
So it returns true if the input string is not null and equals true (ignoring case). Else false is returned.
You seem to expect that Boolean.parseBoolean(String) accepts an expression string and evaluates the string, but that is simply not the case.

While you write System.out.println(1<2); it works because there is a overloaded version of println() which takes boolean value. But when you pass a string, it will be considered as String only, NOT boolean.
In addition, Boolean.parseBoolean() always takes boolean value(true\false) in string format as parameter and returns corresponding value in boolean format, otherwise it will always return false

Boolean.parseBoolean does the following, according to the docs:
public static boolean parseBoolean(String s)
Parses the string argument as a boolean. The boolean returned
represents the value true if the string argument is not null and is
equal, ignoring case, to the string "true".
You're attempting to pass in an expression that will evaluate to true or false, rather than the string "true" or "True" or "TRUE". Therefore, this will work like so:
Boolean.parseBoolean("true"); // equals true
Boolean.parseBoolean("1 > 2"); // not the string "true", therefore returns false.
Generally speaking, you should be very cautious about dynamic execution of code contained in strings. If the string is being passed in from a user, it's quite dangerous. My advice would be to find a better way.
If you really need to do this:
One of the other answers mention using ScriptEngine. Please be aware that this evaluates the string as JavaScript, not as Java. For simple boolean expressions, that's probably fine, but you should be aware of it. JavaScript has rules for truthiness that are perplexing at times, and they will not evaluate the same in Java.
For example, try running this in ScriptEngine:
1 > '0' // true in JavaScript, but probably unexpected in your code!
If you want to do this all properly in Java, you could use the Java Compiler API. Unfortunately, it's not as simple as simply feeding expressions as strings to the ScriptEngine. This post might be useful, however, for in-memory compilation of Java code.

Related

Comparing an int initialization with a boolean operator for an if statement parameter

I've declared ints skyB and day, and written this line:
if (skyB == true || (day=1) != true) {
System.out.print("example text");
}
Am I correct in assuming that the code will properly execute the argument given these parameters? I'm specifically unsure about whether or not the (day="1") would be properly detected as false, given the instance that the objects input was indeed a false.
minimal reproducable example(not including main method or packages):
int skyB = false;
int day =2;
if (skyB == true || (day =1) != true) {
System.out.print("example text"); }
The simple answer: this isn't C++
You cannot assign numeric value to boolean fields. In Java, the only two valid values are true and false. Therefore, you cannot assign integer values to a boolean variable.
For your boolean expressions to be valid, your variables skyB and day must be boolean data types
boolean skyB = false
boolean day = true
if (!skyB || day) {
System.out.print("example text");
}
The boolean fields are evaluated without the need to compare them to true or false. The expression !skyB (read "not skyB") evaluates to false. So this is the equivalent to skyB == false. Since that portion evaluates to true (skyB is equal to false), the second part of the expression is skipped and the System.out.print() is called. If the value of skyB was changed to true, the variable day would then be evaluated and the if-statement would be executed if the value of that variable equals true (which it is).
Alternatively, you could build boolean expressions using numeric values. How? Simple. Any mathematical expression is evaluated the same. For example:
int x = 5;
int y = 3;
if (x > y) {
System.out.println("x is greater than y");
}
Basically... The logic of what you are trying to do (the way I understood it) is correct, but your implementation was not. You cannnot mix boolean fields and numeric values. It is simply not allowed in Java.
Now, to your question...
boolean skyB = false; // this must be boolean, not int
int day =2; // this is fine
if (skyB || day == 1) {
System.out.print("example text");
}
Should produce the desired outcome. In plain English, the above is read:
If skyB is false OR is day one, print "example test"
If either part of the expression fails to evaluate to true (i.e. if skyB is true and day variable is any value other than one), it will not print anything.
UPDATE:
Even if this answer has been accepted and upvoted, I would like to include some information about boolean expressions for the benefit of new developers that might be struggling with this concept.
What is a Boolean Expression?
According to Oracle documentation, "A Boolean expression is a logical statement that is either TRUE or FALSE." These expressions take a few different forms. For example,
Boolean literals
if (true) {...}
Although there is no real reason for such if-statement, the above is a valid expression. "If true, do the stuff inside the curly braces." This means that the stuff inside will always execute (making it the same as not having the "if". However, this is the basis for understanding the rest.
Boolean variables
boolean isBlue = false;
if (isBlue) {...}
In the above case, the Boolean expression is the variable itself. The expectation is that, if the variable value evaluates to true, the stuff inside the curly braces will be executed. Since the value is false, it won't be executed. The above "if" is the more accepted short form of
boolean isBlue = false;
if (isBlue == true) {...}
So, since the left hand (variable) value of this evaluation is false and the right side is true, the complete expression evaluates to false. Therefore, the stuff inside curly braces won't be executed (false does not equals true). However
boolean isBlue = false;
if(!isBlue == true){...}
Negating a boolean variable toggles it's value. In this case, the isBlue variable holds the value of false. The "not" operator toggles its value to true. Since true == true evaluates to true (true equals true is a true expression), the stuff inside curly braces is executed.
Functions that yield a boolean value
public boolean isSkyBlue() {
return true; // sorry for the over simplification
}
...
if (isSkyBlue()) {...}
This is nothing more than an advance form of what I have shown already. In this case, the method "computes" the boolean value to be returned. Since boolean values are expressions onto themselves, it is valid to insert a method call such as the one illustrated above inside the parentheses. The stuff inside curly braces will execute so long the function returns true.
Comparison operations
I included the following example already:
int x = 5;
int y = 3;
if (x > y) {
System.out.println("x is greater than y");
}
Any type of comparison operation will yield true or false. Therefore, these comparison operations are boolean expressions. This also includes the result of overridden Object#equals(Object) method. For example:
String s = "Hello";
if (s.equals("Hello")) {...}
As a side note, objects in Java should be compared using an overridden equals() method, and not using the double-equals operator (unless you are only interested in comparing the object references (address) to be equal.

Resultset.getBoolean()) not returning true for if condition - row has value

Resultset.getBoolean()) not returning true, when value is there.
I'm trying to use a if condition so if there is row value in "fldplayersalary" then enter condition, however it keeps going to else. I have put a breakpoint and there is value for fldplayersalary (15583 for example).
Can someone explain why the .getBoolean is not returning true, because there is definitely a field "fldplayersalary" in table and data also. I've attached a screenshot of MySQL database
image of sql table
ResultSet r = stm.executeQuery("select * from tblmember");
//1-int,2-string,3-string,
while(r.next())
{
if(r.getBoolean("fldplayersalary") == true)
{
System.out.println("Player - 11 fields");
int id = r.getInt("fldmemberid");
String first = r.getString("fldfirstname");
String last = r.getString("fldlastname");
String email = r.getString("fldemail");
String mob = r.getString("fldmobile");
String gender = r.getString("fldgender");
String dob = r.getString("flddob");
String debut = r.getString("flddebut");
String recruited = r.getString("fldrecruitedfrom");
int salary = r.getInt("fldplayersalary");
int team = r.getInt("fldteamid");
Player pp = new Player(id, first, last, email, mob, gender, dob, debut, recruited, salary, team);
plist.add(pp);
}
.getBoolean is for reading boolean values, hence the name.
You seem to believe that the concept of truthy/falsy is universal. It isn't. First, adjust your thinking, then this becomes much simpler.
'truthy'/'falsy' is the notion that all expressions, if forcibly interpreted as a boolean, always report one of those two values. Many programming languages and environments are completely truthy/falsy, such as javascript and python.
However, java is not. In java, true is true, false is false, and nothing else is:
String x = "true";
if (x) {}
simply fails to compile in java, as x is neither the boolean value true nor the boolean value false (specifically, the type of the expression x isn't boolean, and the compiler immediately calls it at that point and flags an error). You appear to be so used to languages that have this complicated definition of what is considered 'true' (truthy) and what is considered 'false' (falsy), such as 'lists are truthy unless empty, null and undefined are falsy, numbers are truthy unless 0 or NaN, strings are truthy unless empty, nobody can remember if the string "false" or "0" is truthy or falsy, objects are truthy unless they override an operator method to say they are falsy, even a boolean wrapper wrapping the value 'false' ends up being truthy because of that, yadayada'. Hopefully you now also know why truthy/falsy is not universally applied: It's quite confusing at times. Java doesn't engage in it; java doesn't ever guess what you intended when you pass a non-boolean to a thing where only booleans are allowed. It just errors and demands you perform an operation that explicitly resolves to a boolean value, such as a < b or a.foo() where foo() has boolean as return type, etc.
Now that you know such systems exist, it should be obvious that the meaning of getBoolean is not 'act like python or javascript and do the usual: if null or 0 or empty or (yeah this is where truthy/falsy gets tricky doesnt it? Is the string "Non" falsy?)'.
What you're presumably looking for is either:
if (r.isNull("fldplayersalary")) {
or possibly:
if (r.getInt("fldplayersalary") != 0) {
Note that .getInt returns 0 if the value stored for that row is NULL, hence, if fldplayersalary is NULL, or it is set to 0, that if would not trigger, otherwise, it would, which sounds like what you wanted.

= and == difference in If statement Java

I am facing something strange here. Please help me understand if I am missing something. My if condition was supposed to be:
if(configuredPdf == true)
But by mistake I had written:
if(configuredPdf = true)
And my Eclipse compiler does not ask me to correct it. Then I assume there is no compile time or checked exception. So:
(configuredPdf = true)
Returns a boolean?
Yes, configuredPdf = true assigns true to your variable and returns true. Therefore if (configuredPdf = true) is a valid syntax even though it's usually a bug.
It's safer to use if (configuredPdf) to avoid this kind of typo.
An assignment is an expression which returns the value you assigned. e.g. a = b = true will assign true to a and b.
The reason boolean type was added was to avoid this sort of bug. In C for example you can write
if (a = 1)
and anything non-negative is true.
While you can still make a mistake with boolean types, instead of writing
if (a == true)
if (b == false)
you can write
if (a)
if (!b)
A more common example is
for(String line; ((line = br.readLine()) != null;) {
// process the line.
}
An assignment expression's result is always the value that was assigned, including when assigning to a boolean. This is covered by JLS§15.26:
At run time, the result of the assignment expression is the value of the variable after the assignment has occurred.
So yes, configuredPdf = true assigns true to configuredPdf, and the result of that expression is true.
Similarly, x = y = 5; assigns 5 to y, and the result of y = 5 is 5, which is then assigned to x.
Fundamentally, what you wanted was:
if (configuredPdf)
There's never any need to compare a boolean variable with true or false, just use the if (theVariable) (for comparing with true) or if (!theVariable) (for comparing with false). Getting in that habit will protect you from inadvertent assignment.
The only time actually comparing boolean values is useful is when they're both variables, e.g. if (thisFlag == thatFlag) or if (thisFlag != thatFlag).
To avoid accidental assignment in that situation, either:
Use a linter that checks for this
"double bang" the first flag:
if (!!thisFlag == thatFlag)
...although as you pointed out if you can accidentally type = instead of ==, presumably you can accidentally type ! instead of !! :-)
Use an old C idiom (this is what I use):
if (!thisFlag == !thatFlag)
What is happening is when the compiler comes to the if condition in your code, it assigns 'configuredpdf' to be true. Thus the condition
if(configuredpdf = true)
Becomes true and the loop executes successfully. However, the problem arises when we DON'T want this loop to be true. At that time when, for a given input, the compiler parses the if condition, it forcibly becomes true and executes the code written in if condition executes even if the data entered does not agreeing. That is why you will find that your code has a bug at the if condition.
configuredPdf must be a boolean for if(configuredPdf = true) to compile.
configuredPdf = true will assign true to configuredPdf and thus if will succeed.

Address with zip code. Java

The constructor will throw an IllegalArgumentException exception with the message "Invalid Address Argument" if any parameter is null, or if the zip code has characters others than digits.
The method Character.isDigit can help during the implementation of this method. See the Java API (Character class) for additional information.
I've had the illegal argument exception down. But, not the zip code. Help?
Program.
if(street==null||city==null||state==null){
throw new IllegalArgumentException("Invalid Address Argument");
}
if(zip == Character.isDigit(ch)){
//To do???
}
try apache stringutils
public static boolean isNumeric(CharSequence cs)
Checks if the CharSequence contains only Unicode digits. A decimal point is not a Unicode digit and returns false.
null will return false. An empty CharSequence (length()=0) will return false.
StringUtils.isNumeric(null) = false
StringUtils.isNumeric("") = false
StringUtils.isNumeric(" ") = false
StringUtils.isNumeric("123") = true
StringUtils.isNumeric("12 3") = false
StringUtils.isNumeric("ab2c") = false
StringUtils.isNumeric("12-3") = false
StringUtils.isNumeric("12.3") = false
Parameters:
cs - the CharSequence to check, may be null
Returns:
true if only contains digits, and is non-null
Since:
3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence), 3.0 Changed "" to return false and not true
int zipcode = 0;
try {
zipcode = Integer.parseInt(zipcode);
}catch (Exception e){}
if (zipcode <= 0)
{
throw new Exception(..);
}
And less than 1,000,000 if you want to be precise. You are using Char which makes no sense as you will have a String.
This sounds like homework to me, so I think the first thing you need to do here is learn how to read the documentation. Let's start by taking your instructor's hint, and looking up the documentation for Character.isDigit(char ch)
public static boolean isDigit(char ch)
Handwaving away some of the terms there, the critical things are that the method is static (which means we call it like Character.isDigit(myVariable) and that it returns a boolean (true or false value), and that it accepts a parameter of type char.
So, to call this method, we need a char (single character). I'm assuming that your zip variable is a String. We know that a string is made up of multiple characters. So what we need is a way to get those characters, one at a time, from the String. You can find the documentation for the String class here.
There's a couple of ways to go about it. We could get the characters in an array using toCharArray(), or get a specific character out of the string using charAt(int index)
However you want to tackle it, you need to do this (in pseudocode)
for each char ch in zip
if ch is not a digit
throw new IllegalArgumentException("Invalid Address Argument")

what is the difference when string == is used for comparison with in System.out.println() and in a if statement

String att = "siva";
String ptt = "siva";
System.out.println("__________________________ptt.equals(att)_______"+ptt.equals(att));
**System.out.println("__________________________att == ptt________"+att == ptt);**
if(att == ptt){
System.out.println("true");
}else{
System.out.println("false");
}
On my log i find the following output:
__________________________ptt.equals(att)_______true
**false**
true
here if you look at the java code and the log (in bold). there is a difference .
In the print statement i have given a long underscore with some text. it is not appearing.
att==ptt gives false when it is given with in print statement. and true when it is given in if condition.
already i know,
what is a reference and what is a object.
what is difference between att==ptt and att.equals(ptt).
immutability of a string.
but just what to know why it returns false and true when printed in different forms? and why the text that i have entered in the print statement not reflected in log?
please correct it if am wrong.. or if any extra input is required.
In the print statement i have given a long underscore with some text.
it is not appearing.
Because, those underscore was concatenated with att and checked to referential equality(==) with ptt, and prints false, becuase concataneted String and ptt are not referentially equal. Change it like following to get you desired output
System.out.println("__________________________att == ptt________"+(att == ptt));
att==ptt gives false when it is given with in print statement. and
true when it is given in if condition.
Both are referring same String literal in String constant pool, but, in the previous case(your 1st question), att was concatenated with the under score and compared with ==
Change the Line to:
System.out.println("__________________________att == ptt________"+(att == ptt));
Now your output will be as expected. First it compare the reference of att and ptt and then it is printed. You only forgott the parentheses . Now the result will be the same like in the if-statement. And the result is true because you are using String literals to assign the value "siva". Internally this literals got the same reference. If you creat String objects like new String("siva") the output of your code will be false because you are comparing the reference with == and if you creat two objects the reference is different.

Categories