0

The following code shows the following error:

Exception in thread "main" java.lang.NullPointerException at cdtWorkspace.swap.main(swap.java:25)

PS: I have initialized a scanner object globally as static.

15 public static void main(String args[] ) throws Exception {
16    
17            int n=scn.nextInt();
18            int[][] param=new int[n][2];
19            int[][] arr=new int[n][];
20            for(int i=0; i<n;i++){
21                param[i][0]=scn.nextInt();
22                param[i][1]=scn.nextInt();
23                int j=0;
24                while (j<param[i][0]){
25                    arr[i][j]=scn.nextInt();
26                    j++;
27                }
28            }
29 }

I am getting the same error each time i try to fill in an array using a for loop! Any suggestions?

David Titarenco
  • 32,662
  • 13
  • 66
  • 111
Maverick
  • 31
  • 4

2 Answers2

3

Change 23 - 27 to

arr[i] = new int[param[i][0]];
for( int j = 0; j < param[i][0]; j++ ){  // prefer for to while
    arr[i][j] = scn.nextInt();
}

It should be obvious?

laune
  • 31,114
  • 3
  • 29
  • 42
1

Well

           int[][] arr=new int[n][];

Makes it so arr is an array of n arrays. However those arrays are empty

When you do this

 arr[i][j]=scn.nextInt();

You're accessing columns(because the array at that row has size 0) that don't exist, hence null pointer exception `

committedandroider
  • 8,711
  • 14
  • 71
  • 126
  • Watch your language! An "empty array" is what you get when you say `new int[0]`, but after that `new int[n][]` there aren't any arrays *within* `arr` at all; `arr` contains `n` times `null`. – laune Aug 17 '14 at 07:09
  • when you do matrix[1].length, i saw it was 0 so I assumed it was just an empty array – committedandroider Aug 17 '14 at 22:07
  • Well, `int[][] a = new int[3][]; System.out.println( a[1].length );` does throw a NPE. Please fix your answer. `int[][] a = new int[3][0];` gives you "empty" arrays. – laune Aug 18 '14 at 05:29