当我尝试编译Report.java时,在第6行出现错误,提示:error: <identifier> expected aClient.setClientName("Michael");带有和箭头指向第一个括号。

public class Client {

    private String _clientName;

    public String getClientName(){
        return _clientName;
    }
    public void setClientName(String clientName){
        _clientName = clientName;
    }

}
public class Report {

    Client aClient = new Client();
    //ClientLawn aClientLawn = new ClientLawn();

    aClient.setClientName("Michael");
    //aClientLawn.setLawnWidth(10);
    //aClientLawn.setLawnLength(10);

    public void output(){
        System.out.println(aClient.getClientName());
        //System.out.println(aClientLawn.calcLawnSize());
    }

}


我还想说明一下,我是Java的新手,所以请保持柔和。

最佳答案

使用instance initialization block

public class Report {

    Client aClient = new Client();
    //ClientLawn aClientLawn = new ClientLawn();
    {
        aClient.setClientName("Michael");
        //aClientLawn.setLawnWidth(10);
        //aClientLawn.setLawnLength(10);
    }
    ...
}

关于java - 错误:预期为<identifier>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15934012/

10-10 03:03