1

I have the following problem:

When using a pointer as parameter in a method call I get the "error: identifier expected" error.

This is my code:

class Data {
    Person a = new Person("John");
    Person b = new Person("Mary");

    a.willHug(b);       // Gets error: <identifier> at this line
}

class Person {
    private String name;
    private Person hugs;

    Person(String n){
        this.name = n;
    }

    public void willHug(Person p) {
        hugs = p;
    }    
}

6 Answers 6

5

You shoul put this code inside of a method in order to execute it:

For instance, the main method:

class Data {

    public static void main(String args[]){
         Person a = new Person("John");
         Person b = new Person("Mary");

         a.willHug(b);       // Gets error: <identifier> at this line

    }
}

I think you should read this question of SO in order to understand better how parameters are passed in Java.

Hope it helps.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I had a third class with the main method. By symply creating an object of the Data class and calling the method in the main method, the problem was solved. Thank you again :)
2

You need to surround the operation on a with a method, either a class method, a main() method, or perhaps even a constructor:

class Data {
    Person a = new Person("John");
    Person b = new Person("Mary");

    public Data() {
        a.willHug(b);
    }
}

Comments

2

You need to put your code in a main method:

public static void main (String[] args) {

    Person a = new Person("John");
    Person b = new Person("Mary");

    a.willHug(b);
}

Also in Java we don't call these pointers they are just variables. A variable has a reference to a particular object instance or primitive value.

Comments

1

You are calling a method within the Data class definition? This is not correct, you either need a 'main' to do that, or place that in another method.

Comments

1

You are missing a method there (I introduced a method named foo()) :

class Data {
    Person a = new Person("John");
    Person b = new Person("Mary");

    public void foo() {
        a.willHug(b);       // Gets error: <identifier> at this line
    }
}

class Person {
    private String name;
    private Person hugs;

    Person(String n){
        this.name = n;
    }

    public void willHug(Person p) {
        hugs = p;
    }    
 }

Comments

1

The problem isn't because you use a pointer (called reference in Java) but because this line:

a.willHug(b);

is outside of any method. You can have only declaration or initialization block ({}) in that place.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.