Results 1 to 7 of 7
Thread: Out of Bound Exception Error
- 01-27-2012, 08:33 AM #1
Member
- Join Date
- Nov 2011
- Posts
- 15
- Rep Power
- 0
Out of Bound Exception Error
CodingBat Java Array-1 unlucky1
My code:
What do I do to fix this?Java Code:public boolean unlucky1(int[] nums) { for(int i =0; i<nums.length; i++) { if (nums.length <= 1) { return false; } if((nums[0] == 1 && nums[1] == 3) || (nums[1] == 1 && nums[2] == 3)) { return true; } if((nums[nums.length-1] == 1 && nums[nums.length] == 3) ||(nums[nums.length-2] == 1 && nums[nums.length-1] == 3)) { return true; } } return false; }
- 01-27-2012, 04:54 PM #2
Member
- Join Date
- Jan 2012
- Posts
- 12
- Rep Power
- 0
Re: Out of Bound Exception Error
Array indexes in Java are zero-based. For example if your array has 4 elements in it, they are numbered 0, 1, 2, and 3, NOT 1, 2, 3, 4.
The expression nums[nums.length] effectively attempts to refer to an element that is one greater than the highest-numbered element. Hence the ArrayIndexOutOfBoundsException. Use nums[nums.length-1] to get the last element in your array.
Shameless plug: Moderator edit: removedLast edited by DarrylBurke; 01-27-2012 at 05:18 PM. Reason: Removed shameless plug
- 01-27-2012, 05:19 PM #3
Re: Out of Bound Exception Error
Howard, there's a separate section of these forums for Reviews/Advertising. Please limit any shameless plugs to that area.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 01-27-2012, 06:01 PM #4
Member
- Join Date
- Jan 2012
- Posts
- 12
- Rep Power
- 0
Re: Out of Bound Exception Error
Darryl,
Thanks for pointing that out. I have posted there.
The next time that I spend 2 minutes (or as occasionally happens, 2 hours) researching and answering someone's specific forum question, is it OK if I sign my reply 'Howard Hyde, author, Java Web Database Application Development at JavaWebDB.com'?
- 01-27-2012, 09:17 PM #5
Member
- Join Date
- Nov 2011
- Posts
- 15
- Rep Power
- 0
- 01-27-2012, 09:37 PM #6
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,377
- Blog Entries
- 7
- Rep Power
- 17
- 01-27-2012, 11:48 PM #7
Member
- Join Date
- Nov 2011
- Posts
- 15
- Rep Power
- 0
Similar Threads
-
Index out of bound exception
By sh4rif in forum New To JavaReplies: 7Last Post: 12-07-2011, 12:32 PM -
Array bound exception
By lakshmibvaraprasad in forum New To JavaReplies: 3Last Post: 07-19-2011, 02:02 PM -
array out of bound exception
By farahm in forum New To JavaReplies: 6Last Post: 12-19-2010, 09:10 PM -
Array index out of bound exception error
By rahulkrishnanr in forum Threads and SynchronizationReplies: 7Last Post: 10-12-2010, 05:57 PM -
ArrayIndexout of Bound exception
By Preethi in forum New To JavaReplies: 2Last Post: 02-14-2008, 09:40 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks