Question

Trying to delete the last comma and instead add an end bracket. How to go about this?

My code:

    @Override
    public String toString(){
    String str="[";
    for(double d:data) str+=d+", ";
    return str;

}

Example data:

stat1 data = [  
stat1 data = [50.0, 60.0,  
stat1 data = [70.0, 80.0,  
stat1 data = [90.0, 100.0,  
stat1 data = [100.0, 110.0,  
stat1 data = [
Was it helpful?

Solution

Sometimes it's hard to tell, ahead of time, when an element you're looking at in an iterator is the last one. In cases like this, it often works best to append the comma before each element instead of after, except for the first element. Thus:

String str = "[";
boolean first = true;
for (double d : data)  {
    if (!first) {
        str += ", ";
    }
    str += d;
    first = false;
}
str += "]";

Another possibility is to use the logic you have now but use substring or replace or some other method to remove the extra two characters, like

str = str.replaceFirst(", $", "]");

which uses a regular expression to replace ", " that appears at the end of the string with a right bracket.

OTHER TIPS

It's better to just print the data in the toString method and add the typographical elements like '[' or comma separately accompanied with an if statement. However if you insist to stick just to the toString method, add a boolean field to the class and set it to true if something is the last object and inside the toString method, check that field and do the right decision.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top