Bala Murugan Bala Murugan - 1 month ago 7
Java Question

How to display Arrays Dynamically

public class globe

public static int line1[] = {1,4,7,10,13};
public static int line2[] = {1,5,7,11,13};
public static int line2[] = {1,5,7,11,13};


public class test

for(i=0;i<3;i++)
{
String temp = "line"+i;
System.out.println(globe.temp);// how to get array hole value
}


How to get the array value in globe class. I need to get specific array values. from for loop given line number. I dont Know how to ask this question. Please help me...

Answer

In the current state of your code, this would require reflection. However, if you need to do such a thing, maybe the design of the Globe class is not right in the first place.

You need to express the link between your lines within the code, if you want to use them the way you shew us. What about using a 2-dimensional array?

public static final int[][] lines = {
    {1,4,7,10,13},
    {1,5,7,11,13},
    {1,5,7,11,13}
};

And then use it this way:

for (int[] line : Globe.lines) {
    System.out.println(Arrays.toString(line));
}

Note that the Globe class name should be capitalized, to be consistent with Java conventions.


For the sake of the example, here is how to do it with reflection in the case you don't control the Globe class:

for (int i = 0; i < 3; i++) {
    String fieldName = "line" + i;
    Field lineField = Globe.class.getDeclaredField(fieldName);
    int[] line = lineField.get(null); // null for static fields
    System.out.println(Arrays.toString(line));
}