I am trying to write a program to search the index of a number in a two-dimensional array. While running the code I keep getting into this exception:
Exception in thread "main" java.lang.NullPointerException: Cannot store to int array because "local4/ [local5]" is null
The code is:
import java.util.*;
public class indexSearch
{
public static void main(String[] args)
{
Scanner xyz=new Scanner(System.in);
int no1,no2;
System.out.println("Enter the first dimension of 2D array");
no1=xyz.nextInt();
int nos[][]=new int[no1][];
for(int i =0;i<nos.length ;i++)
{
System.out.println("Enter the second dimension corresponding to first index "+i);
int k=xyz.nextInt();
System.out.println("Enter the values into it now");
for(int j=0;j<k;j--)
{
nos[i][k]=xyz.nextInt();
}
}
int posi1=-1;int posi2=-1;
System.out.println("Enter the no you want to search");
int l=xyz.nextInt();
for(int i=0;i<nos.length;i++)
{
for(int j = 0; j < nos[i].length;j++)
{
if(nos[i][j]==l)
{
i=posi1;
j=posi2;
}
}
}
if(posi1!=-1&&posi2!=-1)
{
System.out.println("The index was"+posi1+" "+posi2);
}
else
{
System.out.println("The no doesnt exist");
}
}
}
I have only recently started learning arrays and all the solutions for index searching a number in a 2D array were with the array being rectangular which has to lead me to think that there is no way to input from user values for a 2D non-rectangular array whose size is also to be taken from the user.