Michael
Michael

Reputation: 524

error: <identifier> expected

When I try to compile the Report.java I'm getting an error on line 6 saying: error: <identifier> expected aClient.setClientName("Michael"); with and arrow pointing to the first parenthese.

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());
    }

}

I also want to make note that I am new to Java so please be gentle.

Upvotes: 0

Views: 1436

Answers (3)

Nicolas Rinaudo
Nicolas Rinaudo

Reputation: 6178

As everybody else pointed out, you cannot execute code outside of a method, so the following lines are illegal:

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

They need to be wrapped within a method, such as the class' constructor:

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

    // ....
}

It looks like you want this code to be executable though, in which case you want to put all that in a main method such as:

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

You can then compile and execute the Report class.

Upvotes: 1

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

Use instance initialization block.

public class Report {

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

Upvotes: 3

gaborsch
gaborsch

Reputation: 15758

This line should be put into an initializer block:

{
    aClient.setClientName("Michael");
}

So it it executed after creating the aClient.

The code here is run for every instance of the Report. Unfortunately you cannot set parameters to it. If you want to do so, put this block into the constructor:

public Report (String clientName) {
    aClient.setClientName(clientName);
    //aClientLawn.setLawnWidth(10);
    //aClientLawn.setLawnLength(10);
}

Upvotes: 3

Related Questions