0

First of all I know there are plenty of solution related to this topic but I am unable to rectify the error in my code. I am writing one program to find the number of duplicates in a given array.
This code gave me ArrayOutOfBoundException Code:

import java.util.Scanner;
class FindDuplicate
{
    void printRepeating(int arr[], int size){
        int count = 0;
        for (int i = 0; i < size; i++){
            if (arr[Math.abs(arr[i])] >= 0)
                arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
            else
                count++;
        }
        System.out.print(count);
    } 
    public static void main(String[] args) 
    {
        FindDuplicate duplicate = new FindDuplicate();
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] arr = new int[n];
        for(int i=0;i<n;i++)
            arr[i] = scan.nextInt();
        duplicate.printRepeating(arr, arr.length);
    }
}

But the similar code like this when I assign the array values directly in the code didn't gave me ArrayOutOfBoundException. Here is the code

class FindDuplicate
{
    void printRepeating(int arr[], int size)
    {
        int count = 0;
        for (int i = 0; i < size; i++)
        {
            if (arr[Math.abs(arr[i])] >= 0)
                arr[Math.abs(arr[i])] = -arr[Math.abs(arr[i])];
            else
                 count++;
        }
           System.out.println(count);         
    }
    public static void main(String[] args) 
    {
        FindDuplicate duplicate = new FindDuplicate();
        int arr[] = {4, 2, 4, 5, 2, 3, 1};
        int arr_size = arr.length;
        duplicate.printRepeating(arr, arr_size);
    }
}

I am unable to identify where the array is getting out of bound.
Somebody please help me to fix this.

  • 3
    "I am unable to identify where the array is getting out of bound." There: `arr[Math.abs(arr[i])]` – tkausl Oct 22 '16 at 21:06
  • 1
    A convenient situation in Java is that thrown Exceptions report the call stack. Please include the call stack. This will show where the exception is being thrown, and therefor, which line of code is causing the problem. – Jameson Oct 22 '16 at 21:06
  • The Exception you receive can tell you at which line the error occurs. The problem is most likely that Math.abs(arr[i]) returns a value out of arr's bounds – Mein Name Oct 22 '16 at 21:06
  • imagine you just enter 3 numbers, but the first one is a 7, so you are trying to access the seventh position of an array of length 3 – leccionesonline Oct 22 '16 at 21:10
  • @tkausl I don't understand when I assign the array values directly in the code at that time I didn't get any ArrayIndexOutOfBoundException . But when I take the value at run time it gives me exception error. Can you please explain me this ? –  Oct 22 '16 at 21:11

0 Answers0