I am trying to remove duplicate elements from this array by the following code it gives me this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 13 out of bounds for length 13 at pro2.Main.main(Main.java:36)
the code:
public static void main(String[] args) {
int[] x = { 2, 2, 3, 5, 6, 3, 5, 6, 7, 8, 9, 1, 7 };
Integer[] o = new Integer[x.length];
for (int i = 0; i < x.length; i++) {
o[i] = Integer.valueOf(x[i]);
}
for (int i = 0; i < x.length; i++) {
for (int j = i + 1; i < x.length; j++) {
if (o[i] == o[j]) {
o[j] = null;
}
}
}
for (int i = 0; i < x.length; i++) {
if(o[i]!=null)
System.out.print(o[i]);
}
}
You have a typo here:
for(int j = i+1 ; i<x.length ; j++) {
^ this should be j
The current (erroneous) loop doesn't stop until it runs past the end of the array. As a result you are trying to get the value of x[12+1] which is x[13], Out of Array bounds.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.