为什么我的arraylist尽管添加了对象仍然保持空白?

时间:2017-02-22 15:01:07

标签: java

我正在尝试制作一种方法,将数字n分解为素数的乘积。例如,因子分解12将导致3×2 ^ 2。第一个代码块将n分解为松散数字,因此12 = 3 x 2 x 2并将它们放在f中。然后假设第二个块将p中的这些数字存储为p而不是松散的数字,方法是将指数计算为数字出现在f中的次数,因此3 ^ 1 x 2 ^ 2而不是3 x 2 x 2。完成一个对象Power,它存储一个数字的基数和指数。

由于某种原因,此代码不断返回空数组。经过多次查看后,我仍然不知道为什么会出现这种情况。有什么我做错了或我误解了吗?

/**
 * factorize n
 *
 * @param n the number to 'powerize'
 * @modifies none
 * @pre {@code 2 <= n}
 * @return factorization of n
 */
public static List<Power> factorize(int n) {
    List<Integer> f = new ArrayList<Integer>(); // f are factors
    for (int i = 2; i <= n; i++) {
        while (n % i == 0) {
            f.add(i);
            n /= i;
        }
    }


    List<Power> p = new ArrayList<Power>(); // p are the factors with powers
    for (int j = 2; j <= n; j++) { //j will be the base
        int e = 0; //exponent
        for (int k = 0; k <= f.size(); k++) {
            if (f.get(k) == j) {
                e++;
            }
        }
        p.add(new Power(j, e));
    }

    return p; //returns factors in powered form
}

我会在必要时添加Power对象的代码。

/**
 * Record containing a base and an exponent.
 *
 * @inv {@code 0 <= base && 0 <= exponent}
 */
public static class Power { // BEGIN RECORD TYPE

    /**
     * The base.
     */
    public int base;

    /**
     * The exponent.
     */
    public int exponent;

    /**
     * Constructs a Power with given base and exponent.
     *
     * @param base the base
     * @param exponent the exponent
     * @pre {@code 0 <= base && 0 <= exponent}
     * @post {@code \result.base == base && \result.exponent == exponent}
     */
    public Power(int base, int exponent) {
        this.base = base;
        this.exponent = exponent;
    }

} // END RECORD TYPE

1 个答案:

答案 0 :(得分:1)

如果您进行调试,您会在首次n周期后看到1变量值为for。这就是为什么第二个周期根本没有开始的原因

相关问题