Question

Using this code:

 public String toString()
{

    StringBuilder s = new StringBuilder();
    for (int i = 0; i < length; i++)
    {                     
        s.append(i).append(":").append(arr[i]).append(", ");                       
    }
    s.delete(s.length()-2, s.length()-1);
    return s.toString();
}

is not passing this test:

@Test
public void testToString()
{
    BetterArray<String> b = new BetterArray<String>();
    assertEquals("", b.toString());
    b.add("hello");
    assertEquals("0:hello", b.toString());
    b.add("bye");
    assertEquals("0:hello, 1:bye", b.toString());
    b.add("adios");
    assertEquals("0:hello, 1:bye, 2:adios", b.toString());
}

It needs to start out as an empty string (""), am i doing that correctly? I'm new to StringBuilder. I'm using the s.delete to remove the trailing comma and space

Was it helpful?

Solution

This will cause a java.lang.StringIndexOutOfBoundsException in the case of empty string since you will not have comma and trailing space.

s.delete(s.length()-2, s.length()-1);

OTHER TIPS

You're only deleting the comma, the delete line needs to be s.delete(s.length()-2, s.length());.

(By convention, the end index of a range points 1 past the last element of the range. This is the same for String.substring() for example.)

Here's one way to do what you want that doesn't rely on any math tricks. If the length is zero, the method returns an empty string.

public String toString() {
    StringBuilder s = new StringBuilder();

    for (int i = 0; i < length; i++) {
        s.append(i);
        s.append(":");
        s.append(arr[i]);
        if (i < (length - 1)) s.append(", ");
    }

    return s.toString();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top