如何分配数组实例变量中的元素?

How do I assign the elements inside an instance variable of arrays?

public class Weapons
{
    private String[] weaponType;
    
    public Weapons()
    {   
        this.weaponType[] = {"Melee", "Range", "Magic"};
    }   

}

它给了我 2 个错误。

Syntax error, insert ";" to complete BlockStatements

Syntax error, insert "AssignmentOperator Expression" to complete Assignment

如何从数组的实例变量正确分配数组中的元素?

    this.weaponType[] = {"Melee", "Range", "Magic"};

应该是

this.weaponType = new String [] {"Melee", "Range", "Magic"};

您在分配时遗漏了类型,您无需在分配时再次添加这些 []

如果因为静态数据而想将该赋值移动到顶部,您可以简单地写

private String[] weaponType ={ "Melee", "Range", "Magic" };