2017-04-07 43 views
1

我的代码:获得NullPointerException异常,同时增加元素ArrayList的

import java.util.Random; 
import java.util.ArrayList; 

public class Percolation { 
    ArrayList<int[]> grid; 
    Random dice = new Random(); 
    public Percolation(int n){ 
     for(int i=0;i<n;i++){ 
      grid.add(new int[n]); 
     } 
     output(grid,n); 
    } 

    public void output(ArrayList<int[]> x,int n){ 
     for(int i=0;i<n;i++) 
      for(int j=0;j<n;j++) 
       System.out.println(x.get(i)[j]); 
    } 
    public static void main(String[] args){ 
     Percolation p = new Percolation(2); 
    } 
} 

使用此代码抛出一个NullPointerExceptiongrid.add(new int[n])。我如何将数据添加到grid

回答

3

您还没有初始化ArrayList

ArrayList<int[]> grid = new ArrayList<>(); 
+0

This works。谢谢 –

0
import java.util.Random; 
import java.util.ArrayList; 

public class Percolation { 
ArrayList<int[]> grid = new ArrayList<>(); // Initialize the array List here before using 
Random dice = new Random(); 
public Percolation(int n){ 
    for(int i=0;i<n;i++){ 
     grid.add(new int[n]); 
    } 
    output(grid,n); 
} 

public void output(ArrayList<int[]> x,int n){ 
    for(int i=0;i<n;i++) 
     for(int j=0;j<n;j++) 
      System.out.println(x.get(i)[j]); 
} 
public static void main(String[] args){ 
    Percolation p = new Percolation(2); 
} 
} 
+0

是的,刚刚意识到,谢谢。 –

0

没有初始化,你不能在列表中添加元素。

而且你还可以通过另一种ArrayList<>例如为:

ArrayList<ArrayList> grid = new ArrayList<>(); 

因为它是非常动态的。

相关问题