arrays - How do I resolve the error "java.lang.ArrayIndexOutOfBoundsException:5" -
i'm new programming , java first language. i'm using eclipse of coding well.
i've been looking arrays trying understand them. found site: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
i made own variation of first code example:
package testarray; public class testarray { public static void main(string[] args) { // declare new array of integers int[] anarray; // sets array length 5 anarray = new int[5]; // setting each array element anarray[0] = 1; anarray[1] = 2; anarray[2] = 3; anarray[3] = 4; anarray[5] = 5; // displaying value of each array element system.out.println("element @ index 0: " + anarray[0]); system.out.println("element @ index 0: " + anarray[1]); system.out.println("element @ index 0: " + anarray[2]); system.out.println("element @ index 0: " + anarray[3]); system.out.println("element @ index 0: " + anarray[4]); } }
i keep getting error in console:
exception in thread "main" java.lang.arrayindexoutofboundsexception: 5 @ testarray.testarray.main(testarray.java:15)
i've tried using code site receive same error. not setup in eclipse right?
any appreciated!
note: if has helpful sites useful beginning programmer, go ahead , add them post!
here problem:
anarray[5] = 5;
replace by:
anarray[4] = 5;
as yo have defined array of size 5, can use index between 0-4:
anarray = new int[5];
if try access index above 4, run arrayindexoutofboundexception.
Comments
Post a Comment