有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

给出奇怪结果的java集成堆栈

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

StackOfIntegraters类似乎不能很好地处理重复项。当我输入120时,将返回素数5、3和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;
    }
}

共 (1) 个答案

  1. # 1 楼答案

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

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