首页 > 解决方案 > Java - 主要因素 - 提示修复?

问题描述

我想用主要因素填充列表。这里有什么问题?

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
            }
        }
    }

标签: javafactors

解决方案


有两点不对:

  1. 您首先测试因子 3,这意味着您永远不会找到 2 个因子。

  2. 您的循环条件 - testFactor > 1- 是错误的。testFactor不断增长,所以循环只会在testFactor溢出到负值时终止。您应该在变为 1 时终止NumberToFactor。即将条件更改为NumberToFactor > 1.

哦,还有另一个问题 -Factors似乎是一个构造函数,但它出现在一个不同名称的类中 - factorClass。构造函数必须与类同名。


推荐阅读