shubham verma shubham verma - 1 month ago 7
Java Question

The code gives NullPointerException for jagged array

The code gives a NullPointerException on the commented line. I'm unable to find out the issue.

package com.lambda.classes;

import java.util.Random;

public class Lambda {

public static void main(String []args)
{
int array[][]=new int[5][];
Random r=new Random();
Random r2=new Random();
for(int i=0;i<5;i++){
int x=r.nextInt(10);
for(int j=0;j<x;j++)
{
int y=r2.nextInt(200);//this line gives a null pointer exception
array[i][j]=y;
}
}

for (int[] is : array) {

for (int i : is) {
System.out.print(i+"\t");
}
System.out.println();
}
Random x=new Random();
System.out.println(x.nextInt(10));
System.out.println(x.nextInt(10));
}
}

Answer Source

In you code error in this line 'array[i][j]=y;'. Because of it 'int array[][]=new int[5][];'

You need set size for inner array too.

Something like this

public static void main(String[] args) {
    int array[][] = new int[5][];
    Random r = new Random();
    Random r2 = new Random();
    for (int i = 0; i < 5; i++) {
        int x = r.nextInt(10);
        array[i] = new int[x];
        for (int j = 0; j < x; j++) {
            int y = r2.nextInt(200);
            array[i][j] = y;
        }
    }
    for (int[] is : array) {
        for (int i : is) {
            System.out.print(i + "\t");
        }
        System.out.println();
    }
    Random x = new Random();
    System.out.println(x.nextInt(10));
    System.out.println(x.nextInt(10));
}