在 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 许可协议
有一个解决方法。
您可以将其转换为数组,然后使用
Arrays.toString(Object[])
打印出来:System.out.println(Arrays.toString(myStack.toArray()));