-1
TextView text;
for (int j = 1; j < 3; j++) 
{
  text+j = new TextView(this);
 }

Expected Output:

text1 = new TextView(this);
text2 = new TextView(this);
text3 = new TextView(this);

But I get the error while runnig this code..

Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
localhost
  • 1
  • 5

3 Answers3

6

This never works in Java . You cannot name a variable dynamically in Java . The name has be checked at the compile time itself. Hence expressions such as this text+j in the L.H.S will never work. You can use arrays.

You can define an array of TextView instead . Like :

final int SIZE = 3;
TextView[] textViews = new Text[SIZE];
for (int j = 0; j < SIZE; j++) 
{
   textViews[j] = new TextView(this);
}

Once all the elements in array TextView[] textViews are initialized , you can access individual elements using index , textViews[0],textViews[1].... . Remember arrays are indexed from 0 to array.length-1, in your case from 0 to 2.

enter image description here

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
2

You cannot append a integer value to a variable name in Java, like you are trying to do. What you want is an array of TextView'sfor your purpose. You can do it as following:

int textViewCount = 3;
TextView[] textViewArray = new TextView[textViewCount];

for(int i = 0; i < textViewCount; i++) {
   textViewArray[i] = new TextView(this);
}

Hope this helps.

Shobhit Puri
  • 25,769
  • 11
  • 95
  • 124
0

In this case you are better off uzing an array.

TextView[] tv = new Textview[3];
for(int i = 0; i < 3; i++)
    tv[i] = new Textview(this);

The code you posted is trying to generate variabkles dynamically, which can not be done.

Devolus
  • 21,661
  • 13
  • 66
  • 113