Actually there can be many more way to do that .. following is just one of them.
while (temp != null) {
sb.append(temp.data);
temp = temp.next;
if(temp != null)
sb.append(",");
}
Question
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, ]
Solution
Actually there can be many more way to do that .. following is just one of them.
while (temp != null) {
sb.append(temp.data);
temp = temp.next;
if(temp != null)
sb.append(",");
}
OTHER TIPS
This is a good logic exercise so I'll just give hints. Instead of unconditionally adding the comma, you only want to add it in certain cases. For example:
A //No comma since string was empty before adding A
A, B //Hint: the comma is coming before the B!
A, B, C //Same hint
So you only want to include the comma if the string you're adding to is not empty (as is the case when you add the B and C, but not A). How can you program that?
And yes, I'm deliberately leaving the [ ]
characters out; implement the logic I specified above first, and then it's trivial to put the brackets in.
Try this sb.substring(0,sb.length()-1);
A simple trick I like in these cases is to check if string builder is not empty and prepend delimeter. Pseudocode:
StringBuilder sb = new StringBuilder();
while(foo.hasNext()) {
if (sb.length() > 0) sb.append(", ");
sb.append(foo.bar());
}
You could try changing your return statement to something like this:
ln = sb.length();
return sb.substring(0,ln-1).append("]").toString();
Just updated your method:
public String toString(){
StringBuilder sb = new StringBuilder("[");
Node<E> temp = topOfStack;
while (temp != null) {
if(sb.length() > 1)
sb.append(", ");
sb.append(temp.data);
temp = temp.next;
}
return sb.append("]").toString();
}
Cheers !!
Try this :)
public String toString(){
StringBuilder sb = new StringBuilder("[");
Node<E> temp = topOfStack;
while (temp != null) {
sb.append(temp.data).append(temp.next == null ? "" : ", ");
temp = temp.next;
}
return sb.append("]").toString();
}