2

I've written my sorting problem as follows, but i am getting an ArrayIndexOutOfBounds exception. which i'm not able to figure it out. plz help.

System.out.println("Enter the total no of digits to sort:-  ");

n = Integer.parseInt(br.readLine());
x = new int[n];

System.out.println("Enter the elements:- ");

for(i = 0; i < n; i++)
    x[i] = Integer.parseInt(br.readLine());

for(i = 0; i < n; i++)
{
    for(j = 0; j < n; j++)
    {
        if(x[j] > x[j+1])  //ascending order
        {
            temp = x[j];
            x[j] = x[j+1];
            x[j+1] = temp;
        }
    }
}
phatskat
  • 1,797
  • 1
  • 15
  • 32
jhe
  • 25
  • 1
  • 2
  • 9

2 Answers2

4

Since j goes up to n, j+1 is out of bound. You need to change it to

for(j=0;j<n-1;j++)

Doing so would make sure that x[j+1] is within bounds.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • i did the same program in netbeans n gt an error saying..."java.lang.NoClassDefFoundError: javaapplication3/Main Exception in thread "main" Java Result: 1"........help on this plz. – jhe May 01 '13 at 13:11
  • @jhe This is likely to be an issue with your netbeans project configuration. Here is a [link to a relevant discussion](http://stackoverflow.com/q/2702185/335858). – Sergey Kalinichenko May 01 '13 at 13:23
0

Error is here:

if(x[j] > x[j+1]) {
 ....

Because j+1 is equal ton

Make this change:

 for(j=0;j + 1<n;j++) {
  ...
hamid
  • 2,033
  • 4
  • 22
  • 42
  • Nop, `j+1` IS `n` on the last loop. Though when setting `int[n]`, the last index is `n - 1`. So `int[n]` or its equivalent on the last loop `int[j+1]` will be outOfBound. *Example*: int[4] creates keys {0, 1, 2, 3} – Menno May 01 '13 at 13:08