I have found a null pointer exception when I was randomly generating a 2D array. I used the same methods before and it never gave me a null pointer exception.
Here is the main method.
public static void main(String[] args)
{
int row = 5;
int column = 6;
double[][] matrix = new double[row][column];
for(int i = 0; i < row; i++)
{
for(int j = 0; j < column; j++)
matrix[i][j] = Math.random()*20;
}
b = getB(matrix, row, column);
printArray(matrix);
System.out.println("");
System.out.println("");
elimination(row, column);
backSubstitution(row,column);
printSolution(column);
}
The debugger told me that the line that caused the exception lies in the findMaxPivotRow method inside the elimination method.
public static void elimination(int rows, int cols)
{
int pivotRow;
double multiplier;
for (int r = 0; r< rows; r++)
{
pivotRow = findMaxPivotRow(r, rows);
swapRow(r, pivotRow);
for (int i = r+1; i < rows; i++)
{
multiplier = matrix[i][r] / matrix[r][r];
b[i] -= (multiplier * b[r]);
for (int j = r; j < rows; j++)
{
matrix[i][j] -= (multiplier * matrix[r][j]);
}
}
}
}
public static int findMaxPivotRow(int k, int rows)
{
double max_value = matrix[k][k];
int max_row = k;
for (int r = k; r < rows; r++)
{
if (Math.abs(matrix[r][k]) > max_value)
{
max_value = matrix[r][k];
max_row = r;
}
}
return max_row;
}
public static void swapRow(int k, int pivotRow)
{
double[] swap;
double multiplier;
double swap_b;
swap = matrix[k];
matrix[k] = matrix[pivotRow];
matrix[pivotRow] = swap;
swap_b = b[k];
b[k] = b[pivotRow];
b[pivotRow] = swap_b;
}
The line that caused the exception is this line
double max_value = matrix[k][k];
I searched the null pointer exception in 2d array online, and it tells me that the error is either the array is not initialized or the code is outside of the bounds. I used the debugger very thoroughly and it showed me that the indices are in the correct positions.
I know there are a lot of codes I have thrown at you, but you can read the main method, the first few lines of elimination and findMaxPivotRow method.
If you can find why that lined caused the null pointer exception, that would be very helpful. Thanks.