Sohaib - 1 year ago 51

Java Question

this is a 2D array that took the value from user put it's gave me NullPointerException error!!

btw I'm beginner so if you can make it more detailed. thanks

`public static void main(String[] args) {`

java.util.Scanner scan = new Scanner(System.in);

int[][] matrix = null;

System.out.println("Enter " + matrix.length + " rows and " +

matrix[0].length + " columns: ");

for (int row = 0; row < matrix.length; row++) {

for (int column = 0; column < matrix[row].length; column++) {

matrix[row][column] = scan.nextInt();

}

}

}

`Exception in thread "main" java.lang.NullPointerException`

Answer Source

you should to define the size of your matrix like that for exemple:

```
public static void main(String[] args) {
java.util.Scanner scan = new Scanner(System.in);
int[][] matrix = new int[5][1];
System.out.println("Enter " + matrix.length + " rows and "
+ matrix[0].length + " columns: ");
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
matrix[row][column] = scan.nextInt();
}
}
}
```