如何修复Java中的非法表达式启动?

时间:2015-01-20 23:58:07

标签: java

我试图设置对象e1的字符串[],但我不断收到illegal start of expression错误。我是Java的新手,我完全不知道出了什么问题。任何帮助表示赞赏。

public class Employeetest {

    public static void main(String[] args) {

        Employee e1 = new Employee();
        e1.person ={"","","","",""};

        e1.printInfo();
    }
}


public class Employee {

    String[] person ={"","","","",""};

    public void printInfo() {
        System.out.println("Name:" + person[0]);
        System.out.println("Gender:" + person[1]);
        System.out.println("Job Title:" + person[2]);
        System.out.println("Organization:" + person[3]);
        System.out.println("Birthday:" + person[4]);
    }
}

1 个答案:

答案 0 :(得分:3)

初始化字符串数组时,如果已在声明中初始化了数组,则不必提供new String[],例如

String[] person ={"","","","",""};

在您更改值的任何其他地方,您必须提供new String[],如下所示:

e1.person = new String[] {"","","","",""};

但是,在这里,您不需要重新初始化person数组。创建Employee对象时,person已初始化,因为您已声明它。您可以删除此行:

e1.person ={"","","","",""};

它会起作用。但除了将数组的元素初始化为""以外的其他内容之外,除了打印空字段外,它不会做太多。