We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › RESOLVED::Testing for null
Page Index Toggle Pages: 1
RESOLVED::Testing for null (Read 435 times)
RESOLVED::Testing for null
Jun 17th, 2008, 12:09am
 
Is there a way to test for null? I have used the following in TCL and it works fine:

Code:

if {$some_variable != ""} { do something }


However in Processing, when null is "found" the NullPointerException is thrown. How would I test for null in the following example? Since Dog is not found in the first line the exception is thrown which I don't want. How do I prevent this behavior?

Code:

String lines[] = {"Elephants have truncks", "Cows produce milk", "Dogs bark", "Cat meow"};
String type_animal = new String();

for(int i = 0; i < lines.length; i++) {
String type[] = match(lines[i], "(D\\w{3})");
//println(type);
type_animal = type[0];
println(type_animal);
}
Re: Testing for null
Reply #1 - Jun 17th, 2008, 12:23am
 
Code:
 String lines[] = {"Elephants have truncks", "Cows produce milk", "Dogs bark", "Cat meow"};
String type_animal = new String();

for(int i = 0; i < lines.length; i++) {
String type[] = match(lines[i], "(D\\w{3})");
//println(type);
//what you actually want to do is:
if(type.length>0)
type_animal = type[0];
//however to answer your question
if(type[0]!=null)
type_animal = type[0];

println(type_animal);
}
UPDATE: Testing for null
Reply #2 - Jun 17th, 2008, 3:16am
 
Thanks for the reply, however it seems like testing for null throws the NullPointerException. Any other ideas?

...
...
Re: Testing for null
Reply #3 - Jun 17th, 2008, 4:37am
 
match() returns null if there's no match, so you first have to check 'type' (the array), not 'type[0]' (an element in the array). really all you need is:

Code:

if (type != null) {
type_animal = type[0];
}

there's no need to check type.length, because the entire match string is enclosed in parens. so either it matched, returning a 1 element array, or it didn't (and will return null).

(edit) and sorry the docs aren't very clear on this... they were written by a monkey who can't write english. (me cramming it in while preparing a release.)
Re: Testing for null
Reply #4 - Jun 17th, 2008, 4:57am
 
Perfect!
Page Index Toggle Pages: 1