0

i am getting OutofBounds error in it. The outofbounds is happenning here "if (arr[j]==arr[i])" the program is find the dulicate numbers and make them 0. and to shift all those dulicate numbers left.

input: {10,20,4,20,5}
output:{0,0,10,4,5}

Code:

import java.util.*;
class ArrayWork
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);
        int arr[],n,i,j,nr=1;
        System.out.println("Enter the value for n: ");
        n = sc.nextInt();
        if(n>25)
            System.out.println("Invalid input");
        else
        {
            arr = new int[n]; 
            System.out.println("Enter the array elements: ");
            for(i=0;i<n;i++)
            {
                arr[i] = sc.nextInt();
            }
            for ( i = 0; i < arr.length; i++) {
     for (j = i + 1 ; j < arr.length; j++) {
          if (arr[j]==arr[i])
          nr=arr[i];

            for(i=0;i<n;i++)
            {
                if(arr[i]==nr)
                {
                    for(j=i-1;j>=0&&arr[j]>0;j--)
                    {
                        arr[j+1]=arr[j];
                    }
                    arr[j+1]=0;
                }
            }

            System.out.println("The array is: ");
            for(i=0;i<n;i++)
            {
                System.out.print(arr[i] + " ");
            }
        }
    }
}
}}

2 Answers2

0

That is because j = i + 1. Probably you should change your for loops to:

for ( i = 0; i < arr.length; i++) {
     for (j = i + 1 ; j < arr.length - 1; j++) {

But anyway, your code looks not good.

Edit: You are changing the value of i and j in the next three for loops. You should really rethink that code. But at least use a new variable in each for loop i.e. k, l, m

AndiCover
  • 1,724
  • 3
  • 17
  • 38
0

The problem is that when i=arr.length-1, j=arr.length and j is out of bounds. And hence arr[j] throws the error. change it to i < arr.length - 1.

nullptr
  • 3,701
  • 2
  • 16
  • 40
  • i am still getting "for ( i = 0; i < arr.length-1; i++) { for (j = i + 1 ; j < arr.length; j++) { if (arr[i]==arr[j])" same error – Childhood Toons Feb 24 '19 at 11:20
  • @ChildhoodToons I'm not completely sure, but I think its because, the inner loops change the value of i. The third nested loop and the array printing loop use i. Try using different variables there. – nullptr Feb 25 '19 at 16:34