Click here to Skip to main content
15,889,843 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to sort array elements in ascending order.Following is my java code, i cannot understand the error"Exception in thread main java.lang.ArrayIndexOutOfBoundsException: 12 at Sort_array.main(Sort_array.java:20)"

What I have tried:

import java.math.*;
class Sort_array
{
public static void main(String args[])
{
int arr[] = new int[12];
int i=0,j = 0,temp;
System.out.print("The actual array is ");
for(i=0;i<10;i++)
{
arr[i] = (int)(Math.random()*100);
System.out.print(arr[i]+" ");
}
System.out.println();
System.out.print("Sorted array is ");
for(i=0;i<=arr.length;i++)
{
for(j=i+1;j<=arr.length;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}

for(i=0;i<10;i++)
System.out.print(arr[i]+" ");
}
}
Posted
Updated 12-Aug-17 14:44pm

Array is zero based so an array of dimensions 12 is indexed from 0 to 11, your for loop condition tests against the array length which is 12 elements so loops 0 to 12, you need it to be array length -1.

for(i=0;i<= arr.length - 1;i++)
 
Share this answer
 
Java is zero based, which that an array of length 12 have elements from 0 to 11.
The right code is
Java
for(i=0;i<arr.length;i++)

Another problem is that arr have 12 elements, but you fill only 10 of them.

There is a tool that allow you to see what your code is doing, its name is debugger. It is also a great learning tool because it show you reality and you can see which expectation match reality.
When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/jdb.html[^]
https://www.jetbrains.com/idea/help/debugging-your-first-java-application.html[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900