只使用变量名称的Java数组迭代

时间:2016-04-19 14:33:36

标签: java

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

我想使用变量名来调用每个字符串数组。

我想要的结果是ax ay bx by cx cy ......

我该怎么办?还是我需要改变它的结构??

2 个答案:

答案 0 :(得分:4)

您需要以不同的方式声明nodes数组。您将其声明为字符串数组,但您需要将其声明为数组数组。检查以下代码:

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

答案 1 :(得分:0)

或者使用一个班级(耶!):

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