Objects of an array is displaying an error “Java returned: 1” when using setters (or anything) with it

You’re not initializing your array elements before using them. You would need to define a constructor for your class like this(Note that Java class names should always start with uppercase):


// 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;
}

Then you should be able to call it from your driver method like this:

Using No argument constructor:

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();
}

Using argument constructor:

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);
}

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top