0

当我尝试编译 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 新手,所以请保持温和。

4

3 回答 3

3

使用instance initialization block.

public class Report {

    Client aClient = new Client();
    //ClientLawn aClientLawn = new ClientLawn();
    {
        aClient.setClientName("Michael");
        //aClientLawn.setLawnWidth(10);
        //aClientLawn.setLawnLength(10);
    }
    ...
}
于 2013-04-10T18:52:31.387 回答
3

此行应放入初始化程序块中:

{
    aClient.setClientName("Michael");
}

所以它在创建aClient.

此处的代码针对Report. 不幸的是,您无法为其设置参数。如果您想这样做,请将此块放入构造函数中:

public Report (String clientName) {
    aClient.setClientName(clientName);
    //aClientLawn.setLawnWidth(10);
    //aClientLawn.setLawnLength(10);
}
于 2013-04-10T18:53:22.360 回答
1

正如其他人指出的那样,您不能在方法之外执行代码,因此以下行是非法的:

Client aClient = new Client();
aClient.setClientName("Michael");

它们需要包装在方法中,例如类的构造函数:

public class Report {
    public Report() {
        Client aClient = new Client();
        aClient.setClientName("Michael");
    }

    // ....
}

看起来您希望此代码是可执行的,在这种情况下,您希望将所有这些放在一个main方法中,例如:

public class Report {
    public static void main(String... args) {
        Client aClient = new Client();
        aClient.setClientName("Michael");
        System.out.println(aClient.getName());
    }
}

然后,您可以编译并执行Report该类。

于 2013-04-10T20:04:27.660 回答