繁体   English   中英

StackOfIntegers给出奇怪的结果

[英]StackOfIntegers Giving Weird Results

我遇到一个使代码返回整数素数分解的问题。 我知道我的代码给出了正确的因素,但是我必须使用StackOfIntegers类。

StackOfIntegers类似乎不能很好地处理重复项。 当我输入120时,将返回素数5、3和2。 此输出缺少另外2个2。

public class test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter the number: ");
        int number = input.nextInt();
        StackOfIntegers stack = new StackOfIntegers(1);
        int factor = 2;
        while (true) {
            if (number % factor == 0) {
                number = number / factor;
                stack.push(factor);
            }
            if (factor > number) {
                break;
            }
            if (number % factor != 0) {
                factor++;
            }
            if (number < 2) {
                break;
            }
        }
        System.out.println("\nPrime Factors: ");
        for(int i = 0; i < stack.getSize(); i++) {
            System.out.println(stack.pop());
        }
        input.close();
    }
}
class StackOfIntegers {
    private int[] elements;
    private int size;
    public static final int MAX_SIZE = 16;

    /** Construct a stack with the default capacity 16 */
    public StackOfIntegers() {
        this(MAX_SIZE);
    }

    /** Construct a stack with the specified maximum capacity */
    public StackOfIntegers(int capacity) {
        elements = new int[capacity];
    }

    /** Push a new integer into the top of the stack */
    public int push(int value) {
        if (size >= elements.length) {
            int[] temp = new int[elements.length * 2];
            System.arraycopy(elements, 0, temp, 0, elements.length);
            elements = temp;
        }

        return elements[size++] = value;
    }

    /** Return and remove the top element from the stack */
    public int pop() {
        return elements[--size];
    }

    /** Return the top element from the stack */
    public int peek() {
        return elements[size - 1];
    }

    /** Test whether the stack is empty */
    public boolean empty() {
        return size == 0;
    }

    /** Return the number of elements in the stack */
    public int getSize() {
        return size;
    }
}

问题是您在递增i但仍将其与堆栈的当前大小进行比较,堆栈的当前大小也在每次迭代中减小。

您可以在for循环之前将堆栈的大小存储为新的变量size ,也可以只进行while循环,而当堆栈不为空时, pop并打印一个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM