0

it is showing error java.lang.ArrayIndexOutOfBoundsException: 5

i tried diiferent values for the 'for' loop everything worked except this one

import java.io.*;
import java.util.*;
public class TestClass {
    public static void main(String[] args) { 
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int[] arr = new int[n];
        for(int i = 0 ; i<n ; i++)
        {
            arr[i] = in.nextInt();
        }
        for( int j = 0 ; j<n ; j++)
        {
            if(arr[j]>arr[j+1])
            {
                int sw;
                sw = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = sw;
                System.out.println(arr[j] + " ");  
            } else
                System.out.println("error");
        }
    }
}
Ruslan
  • 6,090
  • 1
  • 21
  • 36
  • 1
    in "if(arr[j]>arr[j+1])" the j may be "n-1" which is fine but "j+1" becomes n in this case which is bigger than the array you defined. solution: "for( int j = 0 ; j – kai Feb 12 '19 at 22:06

1 Answers1

3

The problem is with the line:

if(arr[j]>arr[j+1])

When you reach the iteration of the for loop where j == n-1, arr[j+1] is trying to access the nth index of an array with a maximum index of n-1 (e.g. if the array is of size 3, the valid indices are 0, 1, and 2, but your code is trying to access index 3).

You need to change your for loop to:

for (int j = 0; j < n - 1; j++)
Jordan
  • 2,273
  • 9
  • 16