0

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?

3
  • the return type of your newlist() method is void. Should be String. Commented Apr 7, 2014 at 20:52
  • 4
    Why is newList separate method? Also why does it not return anything (its return type is void)? Commented Apr 7, 2014 at 20:52
  • Are ref and quantity arrays? Do you intend to print each element of these arrays on separate lines? Commented Apr 7, 2014 at 21:02

2 Answers 2

3
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.

Sign up to request clarification or add additional context in comments.

Comments

1
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();
}

5 Comments

what about a line break?
Do you try to iterate an array with +quantity+i+.
I doubt whether this actually does exactly what NadNet wants. What would be the point of repeating ref and quantity? Most likely, these are actually arrays which NadNet wants to iterate through.
his question was how to get a value from his list in the .toString(). i'm not a mind reader.
Yes, you're not a mind reader. And that's why Stack Overflow makes it possible to comment on questions - so that we can seek clarification when the question is unclear, before jumping in and answering it. The question does say "I am looking to pass a long list of results" - which should be enough of a hint that this approach is not going to do what the OP needs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.