Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 从另一个类调用方法-给出语法错误_Java_Oop - Fatal编程技术网

Java 从另一个类调用方法-给出语法错误

Java 从另一个类调用方法-给出语法错误,java,oop,Java,Oop,所以我有一个包含arraylist的类和一个定义对象的第二个类。我有一个第三个类,它实例化第一个类一次,然后多次实例化第二个类,并将第一个实例作为参数传递-每次实例化第二个类时,它都应该调用第一个类的方法将自己添加到arraylist中 我在调用第1个方法时遇到一个错误,尽管在标记错位的构造上说语法错误。我的代码是: 头等舱: public class One { private ArrayList<Two> list; One(){list = new ArrayList&

所以我有一个包含arraylist的类和一个定义对象的第二个类。我有一个第三个类,它实例化第一个类一次,然后多次实例化第二个类,并将第一个实例作为参数传递-每次实例化第二个类时,它都应该调用第一个类的方法将自己添加到arraylist中

我在调用第1个方法时遇到一个错误,尽管在标记错位的构造上说语法错误。我的代码是:

头等舱:

public class One {

 private ArrayList<Two> list;

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

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

错误是因为您已按此处所述关闭了构造函数(请检查大括号)

不允许块/方法/构造函数之外的可执行代码,因此这一行

oneInstance.add(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);

 }

只是一个建议:更好的缩进可以帮助您轻松捕获语法错误。

如果出于某种原因,您不希望您的代码位于构造函数中(例如,如果您要添加更多构造函数,并且希望它为所有构造函数运行)或方法中,则必须将其用大括号括起来:

{
   oneInstance.add(this);
}

但是这个特性(称为an)很少在Java中使用。通常不需要它。

啊,是的,你说得对!非常感谢!!是的,这是我最初认为无论如何都会发生的事情,但在我的情况下,这并不是必须的。谢谢你的提示-很高兴知道!您的代码将不会编译,因为它至少有一个编译器错误“private one instance”vs“this.OneInstance”(大写vs.小写)啊,这很公平-已重命名变量以尝试使其更具可读性,但显然没有做到这一点。
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);

 }
{
   oneInstance.add(this);
}