【问题标题】:Objects of an array is displaying an error "Java returned: 1" when using setters (or anything) with it使用 setter(或任何东西)时,数组的对象显示错误“Java 返回:1”
【发布时间】:2021-02-11 14:53:00
【问题描述】:

我对编程很陌生。 我有一个主类和另一个类,myClass。 当我运行程序时,主类中出现错误。 它应该是一个对象数组,并且循环应该为每个对象设置/更改/声明事物。

主类的代码:

myClass[] myObj= new myClass[100];

for(int i = 0; i<amount;i++){
myObj[i].setF(sc.next());
myObj[i].setG(sc.next());
myObj[i].myMethod[0]=sc.nextInt();
myObj[i].myMethod[1]=sc.nextInt();
myObj[i].myMethod[2]=sc.nextInt();
}

错误说“Java 返回:1”,链接将我重定向到:&lt;java classname="@{classname}" dir="${work.dir}" failonerror="${java.failonerror}" fork="true" jvm="${platform.java}"&gt;

myObj 类中没有任何问题,从我通过测试可以看出,错误具体来自 myObj[i]。 我不知道如何解决它。

【问题讨论】:

  • 你必须像myObj[i] = new myClass();一样在for循环之后初始化你的类

标签: java arrays loops class object


【解决方案1】:

您没有在使用数组元素之前对其进行初始化。您需要像这样为您的类定义一个构造函数(请注意,Java 类名应始终以大写开头):


// With your current approach you would at least need to allocate memory for member array
public MyClass() {
    this.myMethod = new int[3];
}

or

// You can also use a constructor like this
public MyClass(String f, String g, int[] methodArr) {
    this.f = f;
    this.g = g;
    this.myMethod = methodArr;
}

那么你应该可以像这样从你的驱动方法中调用它:

使用无参数构造函数:

for (int i = 0; i < amount; i++) {
    myObj[i] = new MyClass();

    myObj[i].setF(sc.next());
    myObj[i].setG(sc.next());
    myObj[i].myMethod[0] = sc.nextInt();
    myObj[i].myMethod[1] = sc.nextInt();
    myObj[i].myMethod[2] = sc.nextInt();
}

使用参数构造函数:

for (int i = 0; i < amount; i++) {
    int[] myMethodArr = new int[3];

    String fInput = sc.next();
    String gInput = sc.next();
    myMethodArr[0] = sc.nextInt();
    myMethodArr[1] = sc.nextInt();
    myMethodArr[2] = sc.nextInt();
    
    myObj[i] = new MyClass(fInput, gInput, myMethodArr);
}

【讨论】:

  • 非常感谢!这很清楚。我决定制作一个构造函数,因为我无法以第一种方式使其工作。当我之前尝试制作一个构造函数时,我没有意识到我需要使用 this.f 等我真的很感激。
【解决方案2】:

在 Java 中,当您创建一个数组时,您只是在创建一个引用数组。这意味着您的对象实例不会自动出现。

这一事实的影响是,您必须先创建数组,然后使用对对象的引用来填充它,您也必须创建这些对象。以下是如何做到这一点:

myClass[] myObj= new myClass[100];

for(int i = 0; i<amount;i++){
    myObj[i] = new myClass(); // here you populate the array with instances
    myObj[i].setF(sc.next());
    myObj[i].setG(sc.next());
    myObj[i].myMethod[0]=sc.nextInt();
    myObj[i].myMethod[1]=sc.nextInt();
    myObj[i].myMethod[2]=sc.nextInt();
}

【讨论】:

  • 谢谢,我试过了,但还是有问题。在 myClass 中,我是否需要将 myClass 设置为构造函数才能使其正常工作?当我这样做时,这很有效,但它给我带来了其他问题,所以如果可能的话,我宁愿逐行做。
猜你喜欢
  • 1970-01-01
  • 2015-02-11
  • 2013-12-09
  • 2019-12-23
  • 2023-03-14
  • 1970-01-01
  • 2016-11-10
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多