我试图通过以下代码从该数组中删除重复元素,但它给了我这个错误:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 13 out of bounds for length 13 at pro2.Main.main(Main.java:36)
代码:
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]);
}
}
最佳答案
您这里有一个拼写错误:
for(int j = i+1 ; i<x.length ; j++) {
^ this should be j
当前(错误)循环不会停止,直到运行到数组末尾为止。 因此,您试图获取 x[12+1] 的值,即 x[13],超出数组范围。
关于java - 从 int 数组中删除重复元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58000419/