2

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.

1 Answer 1

3

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));
}
Sign up to request clarification or add additional context in comments.

Comments

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.