NadNet
NadNet

Reputation: 13

how to insert a loop in a String toString() method in java

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

Answers (2)

Mani
Mani

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

T McKeown
T McKeown

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

Related Questions