[英]Java - Prime Factors - Tip to fix?
我想用主要因素填充列表。 這里有什么問題?
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
條件更改為NumberToFactor > 1
。
哦,還有另一個問題 -
Factors
似乎是一個構造函數,但它出現在一個不同名稱的類中 -
factorClass
。
構造函數必須與類同名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.