【发布时间】:2015-09-17 22:48:52
【问题描述】:
我正在尝试创建一个函数来检查数组中的任何两个索引是否具有相同的值。我意识到我下面的代码只检查第一个索引是否与第二个索引相同,而不检查第一个索引是否与第三个、第四个等相同。
我尝试在 for 循环中使用 for 循环来比较每个索引,但我不知道如何让它工作。
由于我当前的实现,由于 i+1 超出了数组的长度,我还得到了一个索引越界异常。
如果有人可以帮助解决代码并向我解释它是如何工作的,那就太好了!谢谢!
public class Values {
public static void main (String[]args){
int[] A = {0,1,2,1,4};
for(int i = 0;i<=A.length;i++){
int n = i+1;
if(A[i] == A[n]){
System.out.println("Index " + i + " is the same value as index " + n);
System.out.println("Therefore, not all of the values in the array are different");
break;
}
}
System.out.println("All indexes in the array contain different values");
}
}
【问题讨论】:
-
数组元素,你的意思是,不是索引?索引必须是唯一的。
-
提示:需要比较 A[i] 和 A[i + 1],还需要比较 A[i + 2], A[i + 3]... A[length - 1] .