用Java打印堆栈值 [英] Printing the stack values in 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?
到目前为止,我的代码:
My code so far:
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());
此答案对我有用:
在堆栈上使用 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打印堆栈值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!