I need to see if a text field has an empty value. I need to see if
if(Double.parseDouble(distanceTf.getText())==0)
I know 0 won't work. I also know null won't work and I know .equals won't work.
Does anyone know how I can compare this line of code to a null value?
if (stageTf.getText().equals("") || Double.parseDouble(distanceTf.getText()) == null) {
JOptionPane.showMessageDialog(null, "You did not enter both a stage number and distance");
return;
}
Thanks for all the above replies but they don't work.
The part of the code I have trouble with is:
if (Double.parseDouble(distanceTf.getText())==null)
The rest of it is fine.
I have tried putting this outside the if statement and using distanceTf.getText().equals("")
in the if statement but this doesn't work either.
I just can't find out how to assign an empty value to the line of code for a double.
I know null, .equals or "" won't work.
You're not clear on which value could be null, so I'll assume both.
Since Double.parseDouble requires a non-null argument, you need to check it for null.
if(null != distanceTf.getText() && Double.parseDouble(distanceTf.getText()) != 0.0)
stageTf.getText() could return null too, but if you're guaranteed to be comparing a known non-null String against null, it would return false. So, this comparison is safer:
if("".equals(stageTf.getText())
The important thing to understand is: what you mean with null value? A null reference or an empty string?
You could do
stageTf.getText().isEmpty()
to check if the string is empty and parse it only if it contains something.
// here remember it's still wrong
if (!stageTf.getText().isEmpty() && Double.parseDouble(distanceTf.getText()) == null) {
Second problem: Double.parseDouble doesn't return null since it returns a native type.. it thrown an exception if something went wrong. So you can catch NumberFormatException.
Then you could write:
try {
double result;
if (!stageTf.getText().isEmpty() && (result = Double.parseDouble(distanceTf.getText()))) {
/* i think you need the result of the conversion, so i saved it in result */
}
}
catch (NumberFormatException e) { /* something went wrong! */ }
You need to test if the field is empty first. You did it correctly with your first conditional on the stageTf field. You need to do the same with the distanceTF field. This means nesting your conditional statements.
if(stageTF.getText().equals(""))
if(distanceTF.getText().equals("")){
/* ... */
} else {
//here it is safe to test for exceptions by using a try/catch
try{
//here you can parse the string to your Double
}catch(NumberFormatException nfe){ /* ... */ }
}
first of all you should check for null before empty because if the value is null you'll get a NullPointerException on the first one.
Second you'll get a NullPointerException if distanceTf.getText() is null on the Double.parseDouble
Double.parseDouble() doc
what I would do is create a method validate as follows:
private boolean validate(String field){ //where field = stageIf.getText() for example
if(field != null && field.trim().length() > 0)
return true;
else return false;
}
Parse outside if statment, then just compare :
if(distanceTf.getText() == "")
Related
UPDATE: Apologies for the confusion. All code MUST be written between the forward slashes i.e. the "//" beginning at the TO DO comment. And ends the line before the return answer.
Consequently this:
return price<20 ? "Buying new shirt" : null
is unfeasible as return answer is OUTSIDE the allowed code modification area.
I also didn't know if it was possible to assign a null object to a String object (as my comment indicated. And yes, I'm aware of the difference between "null" v null. That is the entire issue I'm having with the code failing to compile.
The ConditionalStatements() method is supposed to pass an integer input and return a string variable called answer.
If the passed integer price < 20 (to include negative integers), then the return variable answer = "Buying new shirt". Otherwise the compiler's expected return value for answer must be null i.e. the OBJECT null and NOT the string "null" which answer is initialized with.
Constraints:
if statement MUST be a Simple Conditional Statement with no branching.
cannot use catch try or other statements. Limited to use of compound conditionals and variables.
MUST be WITHIN the area designated by // forward slashes.
Because of this last constraint, I can't see a way to typecast/return the null as the test errors are indicating. Apologies again for the confusion.
I've tried short circuiting using && and the || operators. Tried getting creative with && and II operators in the if statement to make compound statements. e.g:
if ( (answer.equals(null) && (price >=20) ) etc.
to trap the incorrect test input and change answer data type. But compiler fails test cases of required answer = null for cases where price >= 20. Returning answer = "null" throws an error as a String object is returned v. the desired null.
How to type cast answer variable e.g. (null) answer = null; in my code below?
public class ConditionalStatements {
/**
* This method is used for problem one in the README.
* #param price A price that will be passed in by the test.
* #return String A string used to validate the test.
*/
public String simpleConditional(int price) {
String answer = "null";
**// TODO: Write Step 1 code between the forward slashes** <--start code modification area
(answer == null ) || (price < 20) )
answer = "Buying new shirt";
if( (price >= 20) ) {
answer = null; //this assignment is legal according to post feedback.
//However it STILL results in test failure message (shown in URLs below).
//Where the compiler is expecting a null object and not a string object....
//compiler won't accept answer = null; How to typecast answer String variable so it will accept null object?
}
// **<---this is the END of the code modification area**
return answer;
}
When compiler tries to compile, it fails with these test run errors:
All tests. Only price < 20 passed:
https://i.postimg.cc/TYrH051P/allTests.png
Test 3: price = 20, expected return for answer = null
https://i.postimg.cc/W3GJCVk0/Test3-err1.png
Test 4: price = 21, expected return for answer = null
https://i.postimg.cc/bNJsHk3x/Test4-err2.png
All you have to do assign null to answer variable, rather than "null" string. Check the below code, I think it does what you want to achieve.
public class ConditionalStatements {
/**
* This method is used for problem one in the README.
* #param price A price that will be passed in by the test.
* #return String A string used to validate the test.
*/
public String simpleConditional(int price) {
String answer = null;
// TODO: Write Step 1 code between the forward slashes (answer == null ) || (price < 20) )
if(price < 20){
answer = "Buying new shirt";
}
return answer;
}
public static void main(String[] args){
ConditionalStatements var = new ConditionalStatements();
System.out.println(var.simpleConditional(10)); // prints "Buying new shirt"
System.out.println(var.simpleConditional(25)); // return null object
}
}
To use null with explicit type you have to put a cast in front of null, in you example
if( (price >= 20) ) {
answer = (String) null;
}
The following Java snippet of code confuses me a bit. The method is trying to check whether two objects are NOT equal, using the standard .equals() method to denote that they are equal. Additionally, a boolean can determine whether two null's are considered equal or not. I'm wondering if:
The boolean logic in this method is indeed correct?
the return statement in the middle block can be omitted somehow. Could this logic be rewritten in a more concise or other way, maybe dropping the empty return, but keeping a high level of human readability of the code?
Snippet:
public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual)
{
if(considerBothNullAsEqual && variable == null && otherVariable == null)
{
throw new Exception("not allowed to be equal");
}
if(variable == null || otherVariable == null)
{
return;
}
if(variable.equals(otherVariable))
{
throw new Exception("not allowed to be equal");
}
}
Yes, the logic in the method is correct. It throws the exception if the two objects are equal. You could remove the second condition and combine it with the third one, but I don't see much point. If you did, the method might look like this.
public static void verifyVariableIsNotEqualTo(Object variable, Object otherVariable, boolean considerBothNullAsEqual) throws Exception
{
if(considerBothNullAsEqual && variable == null && otherVariable == null)
{
throw new Exception("not allowed to be equal");
}
if(variable != null && variable.equals(otherVariable))
{
throw new Exception("not allowed to be equal");
}
}
Note that there's no need to check whether otherVariable is null separately, since the equals method on variable should return false if otherVariable is null.
There's an even more concise way to write this, but it's not worth considering, since it sacrifices readability.
I am trying to check if the input in EditText in null or not .
if(editTextSum.getText().toString() != null) {
userStartingBalance = Integer.valueOf(editTextSum.getText().toString());
} else {
userStartingBalance = 0;
}
Here userStartingBalance is Integer type .
But I am getting an error everytime that
Can't convert " " into int , and the line is pointed to the 'if case' if I don't enter anything.
Why is it not going to else case?
What should be the workaround?
You are not properly handling the case in which your EditText simply has no content in it.
In this case, editTextSum.getText().toString() will not return null (in fact, that should never be null). Instead, it will return an empty string.
Instead, you might want to try editTextSum.getText().toString().isEmpty() instead,. isEmpty() will return true if the length is 0.
try:
Integer.parseInt(editTextSum.getText().toString())
Why is it not going to else case ?
Because you are calling ToString() on Null. If the field has no value present then it wil set NULL to it and if you try to run the toString() method you will receive this error. Do the Null check before retrieving the value.
Workaround
if( editTextSum.getText() != null )
{
userStartingBalance = Integer.parseInt(editTextSum.getText().toString());
}
else
{
userStartingBalance =0;
}
I really don't understand why java.lang.NumberFormatException: Invalid long: "null" happens here.
The problem snippet is like followings.
try {
userid = ((JSONObject) msg.obj).getString("userid");
if (userid.equals("") || userid.isEmpty() || null==userid) {
onClickLogout();
return;
} else {
client.setUserid(Long.parseLong(userid));
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
onClickLogout();
return;
}
the line client.setUserid(Long.parseLong(userid)); gets following exception
java.lang.NumberFormatException: Invalid long: "null"
at java.lang.Long.invalidLong(Long.java:125)
at java.lang.Long.parse(Long.java:362)
at java.lang.Long.parseLong(Long.java:353)
at java.lang.Long.parseLong(Long.java:319)
at client.setUserid(Long.parseLong(userid));
The point is that the null exception occurs even after null and empty check of the userid in the code. What's wrong with me here? please check it out experts!
The string value and not reference is null.
You can add "null".equals(userid) to test for the literal null value in the if where you check for various forms of "no value".
Always check first for null value in your condition
if (null==userid || userid.isEmpty() || userid.equals("null") {
Then, in the next element of your condition, you are sure that userid is not null and no NullPointerException will be thrown
Also, in your case, check that userid does not contain the "null" String
Moreover userid.equals("") and userid.isEmpty() are the same thing.
You can check null with utility method isEmpty from TextUtils,
public static boolean isEmpty(CharSequence str) {
return str == null || str.length() == 0;
}
isEmpty(CharSequence str) method check both condition, for null and length.
I have written this function which will set
val=max or min (if val comes null)
or val=val (val comes as an Integer or "max" or "min")
while calling i am probably sending checkValue(val,"min") or checkValue(val,"max")
public String checkValue(String val,String valType)
{
System.out.println("outside if val="+val);
if(!val.equals("min") && !val.equals("max"))
{
System.out.println("Inside if val="+val);
try{
System.out.println("*Inside try val="+val);
Integer.parseInt(val);
}
catch(NumberFormatException nFE)
{
System.out.println("***In catch val="+val);
val=valType;
}
return val;
}
else
{
return val;
}
}
But the problem is if val comes null then
outside if******val=null
is shown.
Can any1 tell me is this a logical mistake?
And why will I correct?
If val is null, then the expression val.equals("min") will throw an exception.
You could correct this by using:
if (!"min".equals(val) && !"max".equals(val))
to let it go inside the if block... but I would personally handle it at the start of the method:
if (val == null) {
// Do whatever you want
}
Btw, for the sake of readability you might want to consider allowing a little more whitespace in your code... at the moment it's very dense, which makes it harder to read.
...the problem is if val comes null then outside if****val=null is shown. Can any1 tell me is this a logical mistake?
The output is correct; whether you want it to come out that way is up to you.
Your next line
if(!val.equals("min") && !val.equals("max")){
...will throw a NullPointerException because you're trying to dereference val, which is null. You'll want to add an explicit check for whether val is null:
if (val == null) {
// Do what you want to do when val == null
}
you should use valType instead of val to check either minimum or maximum is necessary to check.
My advice to you in such cases to use boolean value or enum instead of strings. Consider something like that:
/**
* check the value for minimum if min is true and for maximum otherwise
*/
public String checkValue(String val, boolean min){
if (min) {
// ...
} else {
// ...
}
}
If you need to compare strings against constants you should write it the other way around to make it null-safe:
if (! "min".equals(val))
And while this is mostly a style issue, I would make all method arguments final and not re-assign them (because that is confusing), and you can also return from within the method, not just at the end. Or if you want to return at the end, do it at the very end, not have the same return statement in both the if and the else branch.