我一直得到']'预期错误[Java]

时间:2017-01-20 07:14:51

标签: java arrays

出于某种原因,eclipse在npcname_m [0] =“steve”时不断给我一个']'错误;

    String npcname_m[]=new String[10];
    npcname_m[0]="Steve";
    npcname_m[1]="John";
    npcname_m[2]="Mark";
    npcname_m[3]="Andrew";
    npcname_m[4]="Matthew";
    npcname_m[5]="Luke";
    npcname_m[6]="Miguel";
    npcname_m[7]="Michael";
    npcname_m[8]="Josh";
    npcname_m[9]="Alex";

整个代码

public class npc
{
    //NPC Types; Speci
    public enum npctype{villager, mob, special, hostile, passive, placeholder}
    npctype npc_type =npctype.placeholder;
    String npcname_m[]=new String[10];
    npcname_m[0]="Steve";
    npcname_m[1]="John";
    npcname_m[2]="Mark";
    npcname_m[3]="Andrew";
    npcname_m[4]="Matthew";
    npcname_m[5]="Luke";
    npcname_m[6]="Miguel";
    npcname_m[7]="Michael";
    npcname_m[8]="Josh";
    npcname_m[9]="Alex";

    String[] npcname_f = new String[10];
    npcname_f[0]="Mariah";
    npcname_f[1]="Joyce";
    npcname_f[2]="Kaede Akamatsu";
    npcname_f[3]="Iruma Miu";
    npcname_f[4]="Maki";
    npcname_f[5]="Hannah";
    npcname_f[6]="Angie";
    npcname_f[7]="Grace";
    npcname_f[8]="Melissa";
    npcname_f[9]="Alex";

    public enum npcclass{weak, strong, rare}
    String name = "Placeholder to avoid problems with garbage collector";
    int healthpoints =100;
    int moneyreward =100;
    int attackpower=100;
    Boolean male = true;

    //code to attack player if player starts dsplaying aggressive behaviour torward friendly NPC's
    //Placeholder code
    public void AttackHostilePlayer(){
    return;
    }

    public void TransformHostileVillager(){
        healthpoints= healthpoints + 50;
        attackpower=attackpower + 50;
        System.out.println(npc_type);
        return;
    }

    //Generates an npc (Add randomisation later)
    public void generatenpc(){
        male = true;
        name= "Steve";
        npc_type=npctype.villager;
        return;
    }
}

2 个答案:

答案 0 :(得分:5)

您无法在课程外编写代码'除了Java中的变量定义之外的方法。

public class npc
{   
    String[] npcname_m = new String[10];

    // INVALID CODE ! npcname_m[0]="Steve";

    public npc() {
        npcname_m[0]="Steve";
    }

}

答案 1 :(得分:-2)

改为使用module.exports = {};