0

Given a link list of n floating-point numbers, it returns a two-dimensional link list, say M, of size n × n in which the entry M[i][j] for i ≤ j contains the average of the array entries A[i] through A[j]. That is: if i ≤ j, then M[i][j] = (A[i] + · · · + A[j])/( j − i + 1) , whereas for i > j we have that M[i][j] = 0.

I have already designed this task in Array but Now I want to do it in Arraylist.

public static void main(String[] args) {

    System.out.println("Enter Element");

    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();

    float[][] a = new float[n][n];

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i == j) {
                a[i][j]= sc.nextInt();
            }
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i > j) {
                a[i][j]=0;
            }
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            if (i < j) {
                a[i][j] = 0;
                for (int k = i; k <= j; k++) {
                    a[i][j] += a[k][k];
                }
                a[i][j] /= (j - i + 1);
            }
        }
    }

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            System.out.print("   "+a[i][j]);
        }
        System.out.println("");
    }
}

I have tried with the same idea but I am getting at this stage OutOfBoundException

for (int i = 0; i < lis.length; i++) {
    for (int j = 0; j < lis.length; j++) {

        if (i > j) {
            lis[i][j].add(j, zero);
        }
    }
}
hfontanez
  • 4,939
  • 2
  • 25
  • 33
  • You can do the same using a List that contains List(s). https://stackoverflow.com/questions/1474954/working-with-a-list-of-lists-in-java – pringi Mar 07 '22 at 16:54

0 Answers0