gpt4 book ai didi

java - 在 Java 中打印堆栈值

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:14:04 27 4
gpt4 key购买 nike

在 Java 中,我想打印堆栈 的内容。 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("]", ""));

最佳答案

有一个解决方法。

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

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

关于java - 在 Java 中打印堆栈值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12160183/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com