-5

I can't figure out what the problem is someone please help. The program is supposed to find the index of the duplicate values in the array and print these out. Outputs java.lang.ArrayIndexOutOfBoundsException: 10.

private static String s = "";
private static int num = 0;

public static void main(String[] args) {
    int[] array = { 1, 5, 3, 8, 2, 3, 7, 1, 9, 3 };
    for (int i = 1; i <= array.length; ++i) {
        while (num <= array.length - 2 && array[num] == array[i]) {
            s += i + ","; 
            num += 1;
        }
    }
    System.out.println("index 0 are at positions" +s);
    System.out.println();
}
Chris Martin
  • 30,334
  • 10
  • 78
  • 137
Afshin
  • 11
  • 1
  • 2
  • 2
    The time you spent writing this question would have been better spent typing "java array index out of bounds exception" in google. The top 10 hits have exactly the same problem you're having here. – Vincent van der Weele Jun 13 '14 at 08:40
  • A length of ten means yourArray[0 - 9] position ZERO is the FRIST one, position 1 is the SECOND. – RossC Jun 13 '14 at 08:57

4 Answers4

5
for (int i= 0; i<array.length; ++i) {
    while (num <=array.length-2 && array[num]==array[i]) {
        s += i+ ","; 
        num += 1;
    }
}

This should work for you. length of array is 10, so last index is 9, not 10! And start from 0!

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
PKlumpp
  • 4,913
  • 8
  • 36
  • 64
4

array.length is 10, but last index in array is 9, because array index start from 0.

The stop condition in your for loop should be i<=array.length-1 if you want to loop through entire array.

Mohammad Faisal
  • 5,783
  • 15
  • 70
  • 117
Kasper Ziemianek
  • 1,329
  • 8
  • 15
1

First of all you should start from 0 instead of index 1. And secondly you should use < sign

for (int i = 0; i < array.length; ++i)
AurA
  • 12,135
  • 7
  • 46
  • 63
0

Only the max number of elements is set to 10 which means the index number would start at 0.

You can only get element until the 9th element.

java.lang.ArrayIndexOutOfBoundsException: 10

It is clear sign, that you're not having an 11th element.

for (int i = 1; i < array.length; ++i) {
    while (num <= array.length - 2 && array[num] == array[i]) {
        s += i + ","; 
        num += 1;
    }
}

This would do the job for you.

Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
  • thanks for the help but the above code doesn't print the index of the array at repeat positions. It prints :index 0 are at positions0,1,2,3,4,5,6,7,8,9, – Afshin Jun 13 '14 at 09:51