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("]", ""));