Results 1 to 4 of 4
Thread: quick help, if(n == null) error?
- 06-10-2011, 04:43 PM #1
Member
- Join Date
- Jun 2011
- Posts
- 12
- Rep Power
- 0
quick help, if(n == null) error?
Hi I'm trying to find out if theres anything in a array element.
but != null doesn't work, what other ways could I accomplish this? Ultimately I want anything thats outofbounds be -1.Java Code:public static int position(int[] n, int p) { if (n[p] != null) return n[p]; else return -1; }
Any help would be greatly appreciated!Last edited by JayP; 06-10-2011 at 04:47 PM.
- 06-10-2011, 05:09 PM #2
Moderator
- Join Date
- Jul 2010
- Location
- California
- Posts
- 1,619
- Rep Power
- 5
integer values aren't object, so can't be equated to null. They will be some value, by default in an array 0, so either a) pass an array of object and test for null or b) pass an array with a defined value you can test for to accomplish you needs (no idea what you are trying to accomplish, so this would be based upon the application requirements)
- 06-10-2011, 07:59 PM #3
Member
- Join Date
- May 2011
- Posts
- 35
- Rep Power
- 0
Hi Jayp,
I am not sure what you want. I make 2 assumptions,
1) You want to return -1 if n[p] is null, this is impossible as what doWhile have said. However if you change the int to Integer object, then it is possible.
public static int position(Integer[] n, int p)
{
if (n[p] != null)
return n[p];
else
return -1;
}
2) You want the method to return -1 if arrayIndexOutOfBoundsException is thrown, then you need to use the code below.
public static int position(int[] n, int p)
{
try{
return n[p];
}
catch(ArrayIndexOutOfBoundsException arrayIndexOutOfBoundsException)
{
return -1;
}
}
Thanks
Jing-yi
- 06-10-2011, 09:14 PM #4
Returning -1 when something is wrong is not good practice. It doesn't force the caller to handle the error, so the problem does not become evident immediately, and there is no record of where the error originated. This can lead to strange bugs and invalid data being stored. You should throw an exception instead.
Get in the habit of using standard Java naming conventions!
Similar Threads
-
Solve the Error:null issue
By coopc in forum New To JavaReplies: 2Last Post: 04-12-2011, 06:18 PM -
setColor() gives a null error on execution
By gothrog in forum AWT / SwingReplies: 10Last Post: 09-01-2010, 02:06 AM -
help with with my null error
By zhangster in forum New To JavaReplies: 3Last Post: 03-20-2010, 12:32 AM -
Null point exception Error
By morya123 in forum New To JavaReplies: 10Last Post: 11-25-2009, 11:22 AM -
Null Error
By scoleman123 in forum New To JavaReplies: 2Last Post: 09-19-2008, 04:04 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks