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

解决方法

两件事是错误的:

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

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

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...