gpt4 book ai didi

java - StackOfIntegers 给出奇怪的结果

转载 作者:行者123 更新时间:2023-12-01 11:39:47 26 4
gpt4 key购买 nike

我在编写返回整数素数分解的代码时遇到问题。我知道我的代码给出了正确的因素,但我需要使用 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循环,当堆栈不为空时,弹出并打印一个元素。

关于java - StackOfIntegers 给出奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29632954/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com