问题描述
我想用主要因素填充列表。怎么了?
public class factorClass {
private ArrayList<Integer> factors = new ArrayList<>();
// constructor populates array of factors for a given number
public factorClass(int factorThis) {
int test = 2;
while (factorThis > 1 ) {
if (factorThis % test == 0) { //factor found
factors.add(test); //add factor to array
factorThis = factorThis / test; //quotient is new number to factor
} else {
testFactor++;// try next integer
}
}
}
解决方法
两件事是错误的:
-
首先要测试因子3,这意味着您永远找不到2个因子。
-
您的循环条件-
testFactor > 1
-错误。testFactor
不断增长,因此循环只会在testFactor
溢出到负值时终止。您应在NumberToFactor
变为1时终止。即,将条件更改为NumberToFactor > 1
。
哦,还有另一个问题- Factors
似乎是构造函数,但它出现在具有不同名称的类-factorClass
中。构造函数必须与该类具有相同的名称。