So I created a toString method that changes my stack into a string type. I want my output to be [A, B, C] but in my method it returns an extra ", " in the end which I do not want it to do. How do I make it so that my method does not put the comma space after the last element.
Here's my code:
public String toString(){
StringBuilder sb = new StringBuilder("[");
Node<E> temp = topOfStack;
while (temp != null) {
sb.append(temp.data).append(", ");
temp = temp.next;
}
return sb.append("]").toString();
}
Here's my test:
public void testToString() {
assertEquals("[A, B, C]", stack.toString());
}
Here's the output on my toString method:
[A, B, C, ]