Karem
Karem

Reputation: 18123

Java: for loop using i

I have this:

for(int i=0;i<5;i++){
    lbl1.setText(""+tarningar[i]);

Now I would like to change lbl1 to lbl+i.. so it prints out on lbl0,lbl1,lbl2,lbl3,lbl4.

How can I do this?

Upvotes: 1

Views: 158

Answers (3)

Silfverstrom
Silfverstrom

Reputation: 29358

Add all of the labels to an array, then you can write:

lblarray[i].setText(""+tarningar[i]);

Upvotes: 5

Itay Karo
Itay Karo

Reputation: 18296

Store the labels in array and then:

for(int i=0;i<5;i++){
    labelArray[i].setText(""+tarningar[i]);

Upvotes: 1

Rasmus Faber
Rasmus Faber

Reputation: 49687

Instead of

Label lbl0;
Label lbl1;
Label lbl2;
Label lbl3;
Label lbl4;
/* ... */
for(int i=0;i<5;i++){
  lbl1.setText(""+tarningar[i]);

do this:

Label labels = new Label[5];
/* ... */
for(int i=0;i<5;i++){
  labels[i].setText(""+tarningar[i]);

Upvotes: 1

Related Questions