【发布时间】:2020-03-14 12:50:50
【问题描述】:
我需要编写一个算法,该算法采用int,获取其质因子,将它们放入一个数组并返回它们。
我的代码如下。
public static int[] primfaktorzerlegung(int zahl) {
int d=1; //this is the length of the array
int[] result = new int[d]; //array has to be returned
List<Integer> factors = new ArrayList<Integer>();
for(int factor = 2; factor <= zahl; factor++) {
while(zahl % factor == 0) {
factors.add(factor);
zahl = zahl / factor;
}
}
for(int i : factors){ //trying to get every number of the arraylist
int z = i;
result[d] = z; //trying to put the numbers of the arraylist into the array result
d++; //makes the array dimension one higher
}
return result; //returns the array
}
我收到以下错误:
Error: java.lang.ArrayIndexOutOfBoundsException:
Index 1 out of bounds for length 1
at: result[d] = z;
可能是什么原因?
【问题讨论】:
标签: java primes factorization