1

I'm trying to write a program to practice some basic ADT methods like insert, append etc but my array won't print out the write items. I already programmed it in c++ and i'm trying to redo it in java. Everything looks right but it only prints out 5 zeros(since the length of the array is 5). Here is the code and thanks for the help:

public class newADTClass {
    int length;
    int size;
    int[] Array;

    public newADTClass(int[] Array, int size, int length) {
        Array = new int[10];
        this.Array = Array;
        this.length = length;
        this.size = size;
    }

    void display(newADTClass arr) {
        int i;
        System.out.println("Elements are \n");
        for (i = 0; i < arr.length; i++) {
            System.out.printf("%d ", arr.Array[i]);
        }
    }

    public static void main(String[] args) {
        int[] arr1 = {2, 3, 4, 5, 6};
        newADTClass arr2 = new newADTClass(arr1, 10, 5);
        arr2.display(arr2);
    }
}
1
  • Your program is hard to follow. It can be refactored significantly. But to stay on track, your problem with the code is here: Array = new int [10]. In this line, you replace the constructor Array parameter with a newly initialized array. I think if you remove this line, it will work.
    – A M
    Feb 24, 2021 at 20:04

2 Answers 2

1

You are creating a new blank array in the constructor. If you remove Array = new int [10];, from the constructor then the code will work.

public newADTClass(int[] Array, int size, int length) {
    this.Array = Array;
    this.length = length;
    this.size = size;
}
0

You assign absulutely new created array object to this.Array instead of the Array parameter. By default int[] values are 0.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.