-1
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??

cointreau
  • 864
  • 1
  • 10
  • 21

2 Answers2

4

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);
    }
}
0

Or use a Class (yay!):

class Node {
    String name;
    Node(String name) {
        this.name = name;
    }
    String getX() {
        return name + "x";
    }
    String getY() {
        return name + "y";
    }
}

Node[] nodes = new Node[] {new Node("a"), new Node("b"), new Node("c")};

for (Node node : nodes){
     System.out.printf("%s %s ", node.getX(), node.getY());
}
Adriaan Koster
  • 15,870
  • 5
  • 45
  • 60