У меня есть следующий код. Это конструктор класса Matrix. Основной поток вызывает только конструктор, а затем печатает матрицу (я сделал для нее метод).Исключение NullPointerException, но я не могу понять, как его исправить.
public class Matrix{
float [][] mainMatrix;
int rows;
int columns;
public Matrix(){
System.out.printf("\nInput the number of rows \n") ;
String rowR = new Scanner(System.in).next().replace(" ", "").replace("\n", "").toString();
rows = Integer.parseInt(rowR);
System.out.printf("\n Input the number of columns \n");
String columnR = new Scanner(System.in).next().replace(" ", "").replace("\n", "").toString();
columns = Integer.parseInt(columnR);
System.out.printf("Input the rows, seperated by a \" \". Close the row with a \"]\"");
System.out.println("Warning!!! Inproper input will cause the program to crash!");
for(int r = 0; r < rows; r++){
Scanner item = new Scanner(System.in);
System.out.printf("\n[");
String[] raw = item.next().replace("]", "").replace("\n", "").split(" ");
for(int c = 0; c < columns; c++){
mainMatrix[r][c] = Float.parseFloat(raw[c]);
}
}
/*Bunch of methods*/
}
По какой-то причине, когда код выполняется, он возвращает NullPointerException, и указывает на линии:
mainMatrix[r][c] = Float.parseFloat(raw[c]);
Если это поможет, то результат выглядит следующим образом:
Input the number of columns
2
Input the rows, seperated by a " ". Close the row with a "]"Warning!!! Inproper input will cause the program to crash!
[ 2 3] /*\n*/
[Ljava.lang.String;@29173efException in thread "main" java.lang.NullPointerException
at mathProgs.linProg.Matrix.<init>(Matrix.java:51)
at mathProgs.linProg.MatrixTest.main(MatrixTest.java:10)
2, 3 и] - пользовательские входы. Enter нажимается после «]»
Это 'float [] []', а не 'Float [] []' - и вы также можете заставить компилятор инициализировать все подмассивы в соответствии с моим ответом. –
@JonSkeet мой плохой, код исправлен. –