0

I am getting error as "Exception in thread "main" java.lang.NullPointerException at Pascal.main(Pascal.java:8)"

public class Pascal {
    public static void main(String args[]){

    int rows,i,j,k;
    rows=Integer.parseInt(args[0]);
    double pas[][]= new double[rows][];
    pas[0][0]=1; //the line of error

    for (i=1;i<=rows;i++){
        for (j=1;j<=i;j++){
            pas[i-1][j-1]=pas[i-2][j-2]+pas[i-2][j-1];
        }
    }

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

}

Why I am getting error on line: pas[0][0]=1;

1
  • Because since you did not put a number in the second [], that means all of the 2d arrays are NULL. So you would either need to define that size when initializing the variable OR you would need to add the second array in the for-loop such as: pas[0] = new double[size]; then do pas[0][0] = 1; Commented Feb 4, 2015 at 13:39

4 Answers 4

2

You only initialize the outer array with double pas[][]= new double[rows][];, so pas[0] is still null, and pas[0][0] gives NullPointerException.

Change

pas[0][0]=1;

to

pas[0] = new double[1];
pas[0][0]=1;

You also have to call pas[i] = new double[some-length]; for the other rows.

Sign up to request clarification or add additional context in comments.

Comments

1

you didnt initialise your array properly

double pas[][]= new double[rows][here columns are missing];

1 Comment

That doesn't seem to be the initialization the OP wants, since it looks like he's building a triangle, so the number of columns should be different for each row.
0

In two dimensional array, you have to specify the column size also.

double pas[][]= new double[rows][cols];

Comments

0
package com.survey.ui;

class demo {
public static void main(String args[]){

    int rows,i,j,k;
    rows=Integer.parseInt(args[0]);
    double pas[][]= new double[rows][Integer.parseInt(args[0])];
    pas[0][0]=1;

    for (i=2;i<=rows;i++){
        for (j=2;j<=i;j++){
            pas[i-1][j-1]=pas[i-2][j-2]+pas[i-2][j-1];
        }
    }


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

I am not aware of your business logic but above will run.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.