java - NullPointerException when iterating over arrays -
When I execute this piece of code, I got a nullioner exception.
Exception in the thread "main" matrix on the java.lang.NullPointerException matrix. Calleyhargers average (matrix. Java 31) matrix. (Matrixer.java:75)
Code:
Import java.util.Scanner on Matrixer.main ; Import java.lang *; Class Matrix {Fixed double [] [] matrix, compute matrix; Last intense rows, columns; Public matrix (int n, int m, double [] [] imatrix) {rows = n; Cols = M; Matrix = iatrix; Compute matrix = new double [n] [m]; } Public Zero Mathematical Average (for {{int i = 1; i & lt; rows -1; i ++} {for (int j = 1; j & lt; cols - 1; j ++) {computed Matrix [i] [j] = cell neibor average (i, j); Private Double Cell Nilbars Average (Ent Sol, Int Colley) {// Undiscovered Center Cell Double Zodiac = Matrix [Line-1] [Cola -1] + Matrix [Line -1] [Cola] + Matrix [Line - 1] Matrix [row + 1] + matrix [row] [black-1] + matrix [row] [collect + 1] + matrix [row + 1] [colon1] + matrix [row + 1] [cola] + Matrix [row + 1] [col + 1]; Return amount / 8; } Public void printcomputedmatrix () {for (int i = 0; i & lt; rows; i ++) {for (int j = 0; j & lt; cols; j ++) {System.out.printf (" % .2f ", computedMatrix [i] [ja]); System.out.print (","); } System.out.println (); }} Public static zero main (string [] args throws NullPointerException {scanner sc = new Scanner (System.in); (Int j = 0; j & lt; 5; j ++) for matrix [i] [j] = SCANIT () {int i = 0; I and LT; 5; Try I ++}; } Hold (NullPointerException E) {matrix MX = new matrix (5, 5, matrix); Mx.computeAverage (); Mx.printComputedMatrix (); }}}
What's the problem? And how to fix it?
You have never initiated the matrix that you use in the main Matrix
:
double [] [] matrix, compute matrix;
and then use another array in your head
public static zero main (string [] args throws NullPointerException {scanner sc = new Scanner (System .in); Double [] [] input matrix = new double [5] [5]; Try {For (int i = 0; i <5; i ++) {for (int j = 0; j & lt; 5; j ++) {inputMatrix [i] [j] = sc NextInt (); }} Matrix MX = new matrix (5, 5, input matrix); Mx.computeAverage (); Mx.printComputedMatrix (); } Hold (NullPointerException e) {e.printStackTrace (); }}
Note that I have also changed my argument in main
, which will calculate and display the average if you have NullPointerException.
Comments
Post a Comment