Solved array index out of bounds

February 10, 2012 at 00:58:55
Specs: Windows XP
class Ascending
{
public static void main(String args[])
{
String[] a = { "4", "9", "2", "1", "7", "3"};
int[] b = new int[5];
int i;
for( i=0; i<a.length; i++)
{
System.out.println("get the values:" +a[i]);
b[i] = Integer.parseInt(a[i]);
System.out.println(".......");

}
for(i=0; i<b.length; i++)
{
for(int j=0; j>i; j++)
{
if(b[i]>=b[j])
{
System.out.println("hi");
System.out.println(+b[i]);
}
}
}
System.out.println("*");

}
}


C:\Program Files\java\jdk1.5.0_05\bin>java Ascending
get the values:4
.......
get the values:9
.......
get the values:2
.......
get the values:1
.......
get the values:7
.......
get the values:3
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Ascending.main(Ascending.java:11)


See More: array index out of bounds

Report •


#1
February 10, 2012 at 05:06:00
You are trying to assign something to the sixth element of a five element array (b). Make it 6 elements.

Report •

#2
February 19, 2012 at 03:07:26
✔ Best Answer
First five elements of the String array a are successfully copied to integer array b.But when we try to copy the sixth element of the string array a to integer array b , exception is thrown because the integer array b can accommodate only 5 elements.
This code will work fine if the size of integer array is increased to store 6 elements.
Ex : int[] b = new int[6]

For more info on accessing array elements while working with loops please visit http://www.techyv.com/questions/acc...


Report •

Related Solutions


Ask Question