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());
This answer worked for me:
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("]", ""));
Use toArray()
to print the stack values
public void printStack(Stack<Integer> stack) {
// Method 1:
String values = Arrays.toString(stack.toArray());
System.out.println(values);
// Method 2:
Object[] vals = stack.toArray();
for (Object obj : vals) {
System.out.println(obj);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With