0

Why am I getting this NulPointerException:

Please Give the length of the Array: 
5
Please give the entries for the array for 0th index
2
Exception in thread "main" java.lang.NullPointerException
    at Array.main(Array.java:18)

In this code?

public class Array{

public static void main(String[] args) 
{
    Scanner scan = new Scanner(System.in);
    System.out.println("Please Give the length of the Array: ");
    int num= scan.nextInt();
    int arr[] = null;
    int i;
    for (i=0; i<num;i++)
    {
        if(i<num-1)
        {
            System.out.println("Please give the entries for the array for " +i+"th index");
            arr[i]=scan.nextInt();

        }
        else
        {   
            System.out.println("Please give the entries for the array for last index");
            arr[i]=scan.nextInt();

        }
    }
    scan.close();   
}
}
BSMP
  • 4,596
  • 8
  • 33
  • 44
  • Please take a look at [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask). – Kaan Aug 28 '19 at 19:08
  • Hello Harsh, thanks for the question. When I run this code I get the null pointer exception here: scan.nextInt(). My first impression is the scanner does not recognize the second input value. – ABC123 Aug 28 '19 at 19:18

1 Answers1

2

You need to initialize your array:

int arr[] = new int[num];

Otherwise you cannot put anything in it.

Mick Mnemonic
  • 7,808
  • 2
  • 26
  • 30