Search code examples
javamatrixstaticnullpointerexceptionreturn

java.lang.NullPointerException while trying to print matrix values in java static


Could you please please help me it's my homework in java, i didn't finish it , i just wanted to see if it's working this is the code i'm trying to run, from some reason i get error

java.lang.NullPointerException 

and i think it's something with the static

public  class  Matrix {
public  static int[][] res ;

public static void main () {
    System.out.println(Square());
}

public Matrix () {
    int[][] res = {{1,2,3}, {4,5,6}};
}

public static int getElement (int r, int c) {
    return  res[r][c];
}

public static   int getNumberOfRows () {
    return res.length;
}

public static int getNumberOfColumns () {
    return 1;//return res[0].length;
}

public static int Square() {
    int count;
    int row=getNumberOfRows();
    int col=getNumberOfColumns();
    if (col==row) {
        for(int i=0;i< row ;i++) {
            for(int j=0;j< col ;j++) {
                return 5;

                // if (res[row-i][col-1]!=1) {
                //     return 0;
                // }
                // else {
                // 
                // }
            } 
        }
    }

    return -1;
}

}


Solution

  • Removing the constructor and initialise your static field correctly

    private static final int[][] res = { { 1, 2, 3 }, { 4, 5, 6 } };
    
    // no constructor needed.