Reputation: 97
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;
Upvotes: 0
Views: 57
Reputation: 3175
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.
Upvotes: 0
Reputation: 5023
In two dimensional array, you have to specify the column size also.
double pas[][]= new double[rows][cols];
Upvotes: 0
Reputation: 5798
you didnt initialise your array properly
double pas[][]= new double[rows][here columns are missing];
Upvotes: 1
Reputation: 393801
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.
Upvotes: 2