Printing the stack values in Java(在 Java 中打印堆栈值)
问题描述
在 Java 中,我想打印 Stack 的内容.toString()
方法将它们打印在用逗号分隔的方括号中:[foo, bar, baz]
.
In Java, I want to print the contents of a Stack. The toString()
method prints them encased in square brackets delimited by commas: [foo, bar, baz]
.
如何摆脱它们并只打印变量?
How do I get rid of them and print the variables only?
到目前为止我的代码:
Stack myStack = new Stack ();
for(int j=0; j<arrayForVar.length; j++) {
if(arrayForVar[j][1] != null) {
System.out.printf("%s
", arrayForVar[j][1] + "
");
myStack.push(arrayForVar[j][1]);
}
}
System.out.printf("%s
", myStack.toString());
这个答案对我有用:
在 Stack 上使用 toString
方法,并使用 replaceAll
方法将方括号的所有实例替换为空白字符串.像这样:
Use the toString
method on the Stack, and use replaceAll
method to replace all instances of square brackets with blankstring. Like this:
System.out.print(
myStack.toString().replaceAll("\[", "").replaceAll("]", ""));
推荐答案
有一个解决方法.
你可以把它转换成一个数组,然后用 Arrays.toString(Object[])
:
You could convert it to an array and then print that out with Arrays.toString(Object[])
:
System.out.println(Arrays.toString(myStack.toArray()));
这篇关于在 Java 中打印堆栈值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中打印堆栈值


- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- 转换 ldap 日期 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 获取数字的最后一位 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01