我似乎无法弄清楚为什么java在这里抛出数组索引超出范围的异常:
package for_John;
import java.util.Arrays;
public class merge {
public static void addArray(int iid[], String phen[]){
int i=0;
int j=0;
int x=0;
for(x=0; x<5; x++) {
while(iid[i] == iid[++i] && i <= phen.length){
i=i+1;
}
System.out.println(Arrays.toString((Arrays.copyOfRange(phen, j, i))));
j=i;
i=i+1;
}
}
public static void main(String[] args) {
int iid[]={1,1,1,3,3,3,3,4,4,6,6,7,7,7,8,8};
String phen[]={"a","b","c","w","n","f","h","g","y","u","u","l","l","l","k","p"};
addArray(iid, phen);
}
}
在异常之前输出看起来很好:
Output: [a, b, c]
[w, n, f, h]
[g, y]
[u, u]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 16
at for_John.merge.addArray(merge.java:12)
at for_John.merge.main(merge.java:22)
非常感谢任何帮助!
答案 0 :(得分:2)
在致电i
之前,您应该检查iid.length
是大于还是等于iid[++i]
。
你可以这样做:
while (iid[i] == iid[++i] && i <= phen.length) {
i = i + 1;
if (i + 1 >= iid.length) {
break;
}
}