所以我之前曾问过这个问题,但是现在我想更详细一点,因为我之前没有显示代码,有人说您不是来做我的功课,而是提供帮助。
而且我也从旧问题的答案中获取了for循环……]
我需要编写一个算法,该算法需要一个int值,获取素数并将其放入数组中并返回它们。我的代码如下。
错误:java.lang.ArrayIndexOutOfBoundsException:索引1超出长度1的范围在:结果[d] = z;
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 }
记住:我是新来的:)
所以我之前曾问过这个问题,但是现在我想更详细一点,因为我之前没有显示代码,有人说您不是来做我的功课,而是提供帮助。我也参加了for循环...
您实际上并没有通过增加d
来增加数组的大小。分配数组后,其大小是固定的。