nutia nutia - 7 months ago 18
Java Question

Java array iteration with just variable name

String[] nodes = {"a", "b", "c"};
String[] a = {"ax", "ay"};
String[] b = {"bx", "by"};
String[] c = {"cx", "cy"};

for (String n: nodes){
for (String elem: /* n, it should be sequentially a, b, c */){
System.out.print(elem);
}
}


I want to use the variable name to call each string array.

What I want as the result is,
ax ay bx by cx cy
...

What should I do? or do I need to change its structure??

Answer

You need to declare nodes array in different way. You declared it as a string array, but you need to declare it as array of arrays. Check the code below:

String[] a = {"ax", "ay"};
String[] b = {"bx", "by"};
String[] c = {"cx", "cy"};
String[][] nodes = {a, b, c};

for (String n: nodes){
    for (String elem: n){
         System.out.print(elem);
    }
}