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 Answers6

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.

Community
  • 1
  • 1
Cacho Santa
  • 6,846
  • 6
  • 41
  • 73
  • 1
    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 :) – user1991083 Jan 18 '13 at 17:03
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);
    }
}
nickb
  • 59,313
  • 13
  • 108
  • 143
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.

cowls
  • 24,013
  • 8
  • 48
  • 78
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.

Rob Goodwin
  • 2,676
  • 2
  • 27
  • 47
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;
    }    
 }
Καrτhικ
  • 3,833
  • 2
  • 29
  • 42
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.

Kamil
  • 411
  • 3
  • 9