Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing the stack values in Java

Tags:

java

stack

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("]", ""));
like image 475
Armani Avatar asked Aug 28 '12 13:08

Armani


1 Answers

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);
    }
}
like image 82
Peter Avatar answered Sep 23 '22 18:09

Peter