Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android For loop

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.

like image 532
bjesua Avatar asked Jun 21 '12 02:06

bjesua


People also ask

How to set for loop in Android?

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

What is loop in Android?

September 2, 2020. A loop is a structure in programming that allows you to run the same section of code over and over. This can be used when you want to perform an iterative task (like counting, or sorting through a list) or to create an ongoing, cyclical experience for the user (as in a game loop).

What is for loop in Android Studio?

In Kotlin, the for loop is used to loop through arrays, ranges, and other things that contains a countable number of values.


1 Answers

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());
like image 177
plucury Avatar answered Oct 19 '22 01:10

plucury