Reputation: 13
I am looking to pass a long list of results in a String toString() method,this is my code
public void newlist(){
for(int i = 0 ; i <= nbComposant;i++){
System.out.print(ref+i+" (quantity "+quantity+i+")");
}
}
public String toString(){
return newlist();
}
What's wrong with it?
Upvotes: 0
Views: 678
Reputation: 3364
public String toString(){
StringBuilder builder = new StringBuilder(256);
for(int i = 0 ; i <= nbComposant;i++){
builder.append(ref).append(i).append(" (quantity ").append((quantity+i)).append(")");
}
return builder.toString();
}
You dont need Separate method for this. Use Stringbuilder instead of "+" . Though Recent JVM converts into Stringbuilder it would be good practice to write it.
I dont know what is your excepted Result String. I just copied from your question.
Upvotes: 3
Reputation: 12847
public String newlist(){
StringBuilder sb = new StringBuilder();
for(int i = 0 ; i <= nbComposant;i++){
sb.append(ref+i+" (quantity "+quantity+i+")");
}
return sb.toString();
}
public String toString(){
return newlist();
}
Upvotes: 1