Calling a method from another class – giving syntax error [closed]

So I have a class that contains an arraylist and a 2nd class that defines an object. I have a 3rd class that instantiates the 1st once, and then instantiates the 2nd multiple times passing the instance of the 1st as a parameter- each time the 2nd is instantiated it should call the method of the 1st to add itself to the arraylist.

I’m getting an error calling the method of the 1st though saying syntax error on token misplaced contruct. My code is:

1st class:

public class One {

 private ArrayList<Two> list;

 One(){list = new ArrayList<Two>();}

 public void add(Two TwoInstance){
     list.add(TwoInstance);
 }
}

2nd class:

public class Two {

private String a = null;
private String b = null;
private long c = 0;
private int d = 0;
private int e = 0;
private One OneInstance;

Two(One oneInstance, String a, String b, long c, int d, int e)
{this.oneInstance = oneInstance; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e;} 

oneInstance.add(this);
}

Answer

Error is because you have closed your constructor as mentioned here (check the curly braces)

Two(One oneInstance, String a, String b, long c, int d, int e)
{this.oneInstance = oneInstance; this.a = a; this.b = b; this.c = c; this.d = d; this.e = e;} 

and executable code outside block/method/constructors are not allowed , hence this line

oneInstance.add(this);

will throw an error. Move the above line in your constructor like this:

Two(One oneInstance, String a, String b, long c, int d, int e)
 {
     this.oneInstance = oneInstance; 
     this.a = a; 
     this.b = b;
     this.c = c; 
     this.d = d; 
     this.e = e;
     oneInstance.add(this);

 }

Just an advice: Better indentation can help you catch the syntax errors easily.

Leave a Reply

Your email address will not be published. Required fields are marked *