How to check for an Empty String - java

I am trying to assign a default value to variable if the variable holds an empty string. I used the following codes but they are not working out:
if (d.lat.trim().isEmpty())
latt = 9.0819990;
else {
latt = Double.valueOf(d.lat.trim()).doubleValue();
}
The above code results in an error:
cannot find symbol
symbol : method isEmpty()
location: class java.lang.String
then I used
if (" ".equals(d.lat.trim()))
latt = 9.0819990;
else {
latt = Double.valueOf(d.lat.trim()).doubleValue();
}
The code above jumps the if section and tries to convert the empty String into double thereby throwing error about empty string.
SO, what am I doing wrong?

The empty string is "", not " " (note that there is no space between the quotes).

NPE is correct.
But may I recommend Apache StringUtils .
http://commons.apache.org/lang/api-2.5/org/apache/commons/lang/StringUtils.html#isBlank(java.lang.String)
Checks if a String is whitespace, empty ("") or null.
StringUtils.isBlank(null) = true
StringUtils.isBlank("") = true
StringUtils.isBlank(" ") = true
StringUtils.isBlank("bob") = false
StringUtils.isBlank(" bob ") = false

The first block looks ok to me, but you are probably compiling with Java5, which does not have the String.isEmpty() method yet.

What if you use String.length() == 0 instead of String.isEmpty() ?

Apache StringUtils is a very good way to solve the problems for the validation you're implementing. Nevertheless, it seems very strange the error that you can't use the .isEmpty method, what version of the JDK are you using? Try to change the version of your JDK in the classpath with a latest version (JDK 7) or at least with the JDK 6.
Also remember that empty String is represented by "", just the quotes without any blank. It seems the way you're validating is ok. You can try with something like this.
if (d.lat.trim().isEmpty() || d.lat.length == 0)
latt = 9.0819990;
else {
latt = Double.valueOf(d.lat.trim()).doubleValue();
// or as mentioned before: latt = Double.parseDouble(d.lat.trim());
}

Related

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")

Whats wrong with my syntax on if statement using LineReader?

Can anyone see why I'm getting an error on this:
r = new LineNumberReader(new FileReader(txtFile));
for (int i = 1; i < txtFile.length(); i++){
if (r.getLineNumber() = (6*i)+1 || r.equals(1)) {
//code here
}
}
Error is:
Multiple markers at this line
- The left-hand side of an assignment must be a
variable
- The left-hand side of an assignment must be a
variable
- Syntax error on token ")", delete this token
But i can't see whats the issue is. Error is on the 3rd line
EDIT: I love you all, you've saved me once again! Guess I've spent to long with VB.net....
if (r.getLineNumber() = (6*i)+1 || r.equals(1))
should be
if (r.getLineNumber() == (6*i)+1 || r.equals(1))
Not sure what do you want to check with this r.equals(1) but you will most probably get false all the time, since you are compartir equallity between a LineNumberReader and an Integer.
In JAVA you compare two objects with two equals == , but in the if statement you put only one =.
So replace the = in the second line with the ==.
And please, write down this error somwhere you can remember it. Becouse every time you'll see it, then you'll know that it is caused by this same problem (mostly).
My wild guess would be:
if (r.getLineNumber() == (6*i)+1 || r.getLineNumber == 1)
should be == in stead of =
r.getLineNumber() == (6*i)

Left Hand Side of an Assignment must be a Variable CharAt

I currently have the following code for java.
public class lesson8
{
static Console c; // The output console
public static void main (String[] args)
{
c = new Console ();
String user;
int length, counter, spacecounter;
spacecounter=0;
c.print("Enter a string. ");
user = c.readLine();
length = (user.length()-1);
for (counter=0;counter<length;counter++)
{
if (user.charAt(counter) = "")
{
spacecounter++;
}
}
c.println("There are "+spacecounter+" spaces in your string.");
c.println("There are "+counter+" characters in your string.");
// Place your program here. 'c' is the output console
// main method
}
}
I am getting an error on this part:
if (user.charAt(counter) = "")
The error is
The left-hand side of an assignment must be a variable.
I changed it to "==", but now I get another error:
The type of the left sub-expression "char" is not compatible with the type of the right sub-expression "java.lang.String".
How would I solve this?
Thanks!
So, the reason why
if (user.charAt(counter) = "")
gives that error is that "=" is an assignment operator in java, and so the left-hand side must be a variable. That being said, you probably actually want
if (user.charAt(counter) == ' ')
which uses the comparison operator (==) and the space character (' '). ("" is an empty string)
You are using an asignment over a comparison operator.
Change
if (user.charAt(counter) = "")
to
if (user.charAt(counter) == "")
Update:
You also have an error at comparison again.
You should also use single quotes ( ' ) to compare a char, otherwise it won't get compiled.
if (user.charAt(counter) == '')
But this too will not get compiled as a zero length char is not defined.
You should be comparing a valid character, say ' ' for space.
You want to use the equality operator ==, not the assignment operator = .
"==" is going to make sure that the value to the right is the same as the variable to the left.
"=" is an assignment operator and is used to give value TO the variable, rather than compare it.
I got same error in my code. Adding parenthesis solved this error
Changed from
if(isNotNullorEmpty(operator))
ArrayList<String> result = getOperatorAndTypeforName(name );
to
if(isNotNullorEmpty(operator)){
ArrayList<String> result = getOperatorAndTypeforName(name );
}

"Invalid assignment" error from == operator

I was trying to write a simple method:
boolean validate(MyObject o)
{
// propertyA && propertyB are not primitive types.
return o.getPropertyA() == null && o.getPropertyB() == null;
}
And got a strange error on the == null part:
Syntax error on token ==. Invalid
assignment operator.
Maybe my Java is rusty after a season in PLSQL. So I tried a simpler example:
Integer i = 4;
i == null;
// compile error: Syntax error on token ==. Invalid assignment operator.
Integer i2 = 4;
if (i == null); //No problem
How can this be?
I'm using jdk160_05.
To clarify: I'm not trying to assign anything, just do an && operation between two boolean values. I don't want to do this:
if (o.propertyA() == null && o.propertyB() == null) { return true; }
else { return false; }
== is not an assignment operator, it's a boolean equality operator, see:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.2
If you want to set i to null use the simple assignment operator =:
i = null;
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.1
If you want to check that i is null then you need to use the == operator
if (i == null)
I don't think you are confusing assignment and equality comparison. I think your compiler is just giving you a confusing error message. This program:
Integer i = 4;
i ==null;
should give an error something like this:
Program.java:8: not a statement
i ==null;
Your first program should compile correctly. Perhaps there is some invisible unicode character in the text that is confusing the compiler. Try deleting the entire function and typing it in again.
I think I see your problem. I'm sorry the other answers don't address it.
So, Java has this idea that is shared by some other languages that just because something is a valid expression doesn't mean that that thing, by itself, is a valid statement.
For example, this code will complain similarly:
Integer i = 4;
i+3; // this line gives a compilation error
And yet obviously I can use i+3 (go unboxing!) elsewhere to mean "7":
System.out.println(i+3); // this is fine
It gets a bit confusing because unlike some languages that have this expression/statement distinction, java allows you to use any method call - whether it returns a value or not - as a statement. However, most java operators do not - by themselves - form a valid statement.
Likewise, this fails to compile:
Integer i = 4;
i; // this line gives a compilation error
For the full gory details, see http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#32588
In PL/SQL, assigning a value to a variable is done with the := operator. Comparing two values is done with =.
In Java, assigning a value to a variable is done with the = operator. Comparing two values is done with ==, or a .equals() method in some cases.
You can do things like this:
x = i==null;
This will test if i is null and if so, the value true will be assigned to x (assuming that x is a boolean).

Using a string containing variables in JOptionPane

I am trying to build a string using "if" statements, and then using the built string to show in a JOptionPane.
//If the value is zero, don't show the line item
if (intLays > 0)
strBuiltOrder = "intSnickers + \"Snickers\" + \"\\n\"";
In the end there would be one line item for each variable that had a value greater than zero. However, the problem is, when I use it in JOptionPane, it outputs the literal.
intSnickers + \"Snickers\" + \"\\n\"
Is there anyway I can build a string to insert into JOptionPane, or is there another way to withhold variables from the JOptionPane if their value is zero?
Is there a reason why you escape quotes and backslashes? The following probably does what you expect:
if (intLays > 0) {
strBuiltOrder = intSnickers + "Snickers\n";
}
If you want to build a more complex string you can look into StringBuilder or StringBuffer objects.
Along my own presumption, maybe you were looking for this:
//If the value is zero, don't show the line item
if (intLays > 0)
strBuiltOrder = intSnickers + "\"Snickers\"" + "\"\\n\"";
I hope this helps, or at least points you in the right direction, when I understand more about the expected output I can try to help you out further.
Instead of using a String, try using a StringBuilder then you won't have problems with the syntax of that statement. So your code might be something like:
StringBuilder sb = new StringBuilder(...);
...
if (intLays > 0)
sb.append(intSnickers).append("Snickers\n");
Strings are immutable, so it better to use something like the StringBuilder or StringBuffer.
The solution was:
if (intSnickers > 0)
BuiltOrder.append( intSnickers + "Snickers" + "\n");
This is meant to concatenate a string and insert it into a JOptionPane. I am still sort of confused about why it works this way, instead of the way I have it, but, oh well...

Categories