简体   繁体   中英

Filling a ragged array with a loop in java

I was wondering how it was possible to fill a ragged array with a loop in Java. In my example I want to put Pascals Triangle in the Array. When I try to do it ragged, ( // int [][] hako = new int [n][]; -> as I understand it; it gives a java.lang.NullPointerException. Thanks

int      n    = 12, r = 1;
int [][] hako = new int [n][];

for(int i = 0; i < n; i++){
    for(int j = 0; j < r; j++){
        hako[i][j] = newton(i, j);
    }

    r++;
}

static int factorial(int n){
    int k = 1;

    if(n == 0)
        return 1;

    while(n>1){
        k*=n;
        n--;
    }

    return k;
}

static int newton(int i, int j){
    return factorial(i)/((factorial(j))*(factorial(i-j)));
}

You need to initialize hako[i] as an array before you can assign a variable to an index within it ie hako[i][j] .

int      n    = 12, r = 1;
int [][] hako = new int [n][];

for(int i = 0; i < n; i++){
    for(int j = 0; j < r; j++){

        // need to initialize hako[i]
        hako[i] = new int[r];

        hako[i][j] = newton(i, j);
    }

    r++;
}

your hako, is a matrix, but you initialize only one dimension thus your NullPointerException

to fix it try

for(int i = 0; i < n; i++){
    hako[i] = new int[r];
    for(int j = 0; j < r; j++){
      hako[i][j] = newton(i, j);
    }
    r++;
}
public static void main(String[] args) {

    int y[][] = new int[4][];
    int four =4;
    for (int row = 0; row < y.length; row++) {
     y[row] = new int[four--];
    }

    RaggedArray(y);

    for (int row = 0; row < y.length; row++) {
        for (int column = 0; column < y[row].length; column++) {
            System.out.print(y[row][column] + " ");
        }
        System.out.println();
    }
}

public static void RaggedArray(int x[][]) {
    int j;
    for (int i = 0; i < x.length; i++) {
        int k=1;
        for (j = 0;j<x[i].length ; j++) {
            x[i][j] = k++;

        }

    }
}}

You can change the size and fill it with any data. I wish it will be useful for u and anyone see this code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM