Click here to Skip to main content
13,259,976 members (49,720 online)
Rate this:
 
Please Sign up or sign in to vote.
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 12-Aug-17 10:45am
Updated 12-Aug-17 15:44pm
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

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++)
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

Java is zero based, which that an array of length 12 have elements from 0 to 11.
The right code is
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.
  Permalink  

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

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web01 | 2.8.171114.1 | Last Updated 12 Aug 2017
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100