在 Java 中打印堆栈值

新手上路,请多包涵

在 Java 中,我想打印 Stack 的内容。 toString() 方法将它们打印在由逗号分隔的方括号中: [foo, bar, baz]

我如何摆脱它们并只打印变量?

到目前为止我的代码:

 Stack myStack = new Stack ();

for(int j=0; j<arrayForVar.length; j++) {
    if(arrayForVar[j][1] != null) {
        System.out.printf("%s \n", arrayForVar[j][1] + "\n");
        myStack.push(arrayForVar[j][1]);
    }
}

System.out.printf("%s \n", myStack.toString());

这个答案对我有用:

在 Stack 上使用 toString 方法,并使用 replaceAll 方法将方括号的所有实例替换为空白字符串。像这样:

 System.out.print(
    myStack.toString().replaceAll("\\[", "").replaceAll("]", ""));

原文由 Armani 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 533
1 个回答

有一个解决方法。

您可以将其转换为数组,然后使用 Arrays.toString(Object[]) 打印出来:

System.out.println(Arrays.toString(myStack.toArray()));

原文由 John Eipe 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题