14

I have the following code...

String t = " "; 
for(int l=0; l<=5; l++){
    t = "Num: " + l + "\n";
}

VarPrueba.setText(t);

I am wanting to loop through a set of numbers, and generate a String that lists them all at the end. The output should be something like this...

1
2
3
4
5

Could someone please help me understand how to correct my code.

3
  • First of all this loop runs 6 times and not 5 :) either change the start parameter to 1 or the end condition to < Commented Jun 21, 2012 at 2:04
  • Do you want it to show the number for each time the loop processes or all in one block at the end ? Commented Jun 21, 2012 at 2:04
  • i just want to show all in one block at the end! Commented Jun 21, 2012 at 2:10

1 Answer 1

23

Change as follow:

t+="Num: " + l + "\n";

And the most effective way to do this is to using StringBuilder, Something like:

StringBuilder t = new StringBuilder(); 
for(int l=0; l<=5; l++){
    t.append("Num:");
    t.append(l+"\n");
}

VarPrueba.setText(t.toString());
Sign up to request clarification or add additional context in comments.

1 Comment

+1 StringBuilder is much better for memory. Otherwise you create a new string every time you iterate through the loop.

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.