在 Java 中打印堆栈,以便该数字可用

Printing the Stack in Java so that number are usable

我目前正在 Java 中构建逆波兰表示法计算器。我已经编写了代码,以便在输入 "d" 时,它会在堆栈上打印数字。但是,打印出来的数字无法用于以后的进一步计算(见下图)。

然而,我希望这些数字一旦打印出来,就可以在命令行上使用,这样我就可以进行以下计算。

到目前为止,这是计算器特定部分的代码:

import java.io.*;
import java.util.Arrays;
import java.util.Stack;

public class SRPN {

private Stack<Integer> stack = new Stack<>();

public void processCommand(String input) {
    if(input.equals("+")) {
        long n1 = stack.pop();
        long n2 = stack.pop();
        long result = n1 + n2;

        if(result > Integer.MAX_VALUE) {
            result = Integer.MAX_VALUE;
        }
        else if(result < Integer.MIN_VALUE) {
            result = Integer.MIN_VALUE;
        }

        stack.push((int)result);
    }

    else if (input.equals("-")) {
        long n1 = stack.pop();
        long n2 = stack.pop();
        long result = n2 - n1;

        if(result > Integer.MAX_VALUE) {
            result = Integer.MAX_VALUE;
        }
        else if(result < Integer.MIN_VALUE) {
            result = Integer.MIN_VALUE;
        }

        stack.push((int)result);
    }

    else if (input.equals("*")) {
        int n1 = stack.pop();
        int n2 = stack.pop();
        int result = n1 * n2;

        if(result > Integer.MAX_VALUE) {
            result = Integer.MAX_VALUE;
        }
        else if(result < Integer.MIN_VALUE) {
            result = Integer.MIN_VALUE;
        }

        stack.push((int)result);
    }

    else if (input.equals("%")) {
        int n1 = stack.pop();
        int n2 = stack.pop();
        int result = n1 % n2;

        stack.push((int)result);
    }

    else if (input.equals("/")) {
        double n1 = stack.pop();
        double n2 = stack.pop();
        double result = n2 / n1;

        stack.push((int)result);
    }

    else if (input.equals("d")) {

        String values = Arrays.toString(stack.toArray());
        System.out.println(values);

    }

    else if (input.contentEquals("=")) {
        System.out.println(stack.peek());
    }

    else // assume it's a number
    {
        stack.push(Integer.valueOf(input));
    }
}

我只是想不通你是如何让打印的堆栈号可用的。

预期输出是 d 打印输入到堆栈的数字:

1234 2345 3456 天 1234 2345 3456 天 + 1234 5801 天 + 7035

(如上所示,d 打印前三个输入的数字,然后 d+ 显示 1234,将堆栈的最后两个数字 2345 和 3456 相加得到 5801,接下来的 d+ 然后添加1234 和 5801 得到 7035)

感谢任何帮助/提示,​​谢谢!

我认为你只是在说,而不是这样做:

System.out.println(values)

您想在各行中打印每个数字。如果是这样,您只需这样做:

for n in values:
    System.out.println(n)

所以不用打印:

[1234, 2345, 3456]

您将打印:

1234
2345
3456