繁体   English   中英

方法变量必须为字符串,但需要数组

[英]Method variable needs to be String but requires array

这是我的一部分代码。 我的insertPoint方法有问题。 我有一个我需要命名的数组。 在insertPoint方法中,我提供了一个String变量,该变量为方法指定了名称。 但是,它的名字不会抱怨“表达式的类型必须是数组类型,但必须解析为字符串”。 我尝试添加“节点名称[]”,但它给我一个错误,提示“复制本地变量名称”。 不确定如何解决此问题。

public class Node {

    String name;

    public void newArray(int number) {
        this.name = "children" + number;
        final Node name[]  = new Node[4]; // Node's name should now be e.g. "children0"
        insertPoint(this.x, this.y, size, this.name);
    }

    public void insertPoint(int x, int y, int size, String name) {
        // Node name[]; // dublicate local variable name
        if (this.x < c) {
            if (name[0] == null) { // the type of the expression must be an array type but it resolved to string
                name[0] = new Node(x, y, 0, 0, length);
            } else {
                newArray(0);
            }
        }
    }

}

Java不支持动态变量声明或更改。 在您的代码中,您试图将Node name命名为children0 Java编译器不会更改变量名称。

        this.name = "children" + number;
        final Node name[]  = new Node[4];

您可以使用Map将动态变量存储为键和值。

Map mMap = new HashMap();
mMap.put("children0",your any value);  //to insert
mMap.get("children0");//to get back

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM