Results 1 to 7 of 7
Thread: ArrayIndexOutOfBounds
- 12-07-2009, 12:50 AM #1
ArrayIndexOutOfBounds
So i need a little help with arrays. Why doesnt this program work. I pretty much did what it said on the sun tutorial.
All help appreciated:)
Java Code:import java.io.*; public class Array { public static void main(String[] args)throws IOException { int[] num; num=new int[3]; num[1]=4; num[2]=3; num[3]=2; System.out.println(num[1]); } }
Java Code:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 at Array.main(Array.java:11)
Are you suggesting that Cocunuts migrate?!! -Monty Python
-
arrays are 0 based. Thus your num int[3] array will go from:
num[0]
num[1]
num[2]
If you try to use
num[3] you'll go beyond the array's bounds.
- 12-07-2009, 12:55 AM #3
oh i didnt know that thanks man it works now:)
Are you suggesting that Cocunuts migrate?!! -Monty Python
- 12-07-2009, 12:56 AM #4
array 'indicies' are always zero based. at first this is confusing, because an array of three elements, and have indicies 0,1,2
in your example, the array index out of bounds exception would be occuring on
Java Code:num[3]=2;
the general rule of thumb is the inxex in the [ ] is always (-1) from the physical element.
(because we as humans think of the first element in the array as the 1st element, not the 0th element).
So this code to work would then be.
Java Code:public class Array { public static void main(String[] args)throws IOException { int[] num; num=new int[3]; num[0]=4; num[1]=3; num[2]=2; System.out.println(num[1]); } }
- 12-07-2009, 12:56 AM #5
d.oh.. too wordy on my reply
- 12-07-2009, 12:58 AM #6
thanks man thats really helpful:) i repped u for it:)
Are you suggesting that Cocunuts migrate?!! -Monty Python
- 12-07-2009, 12:59 AM #7
Bookmarks