我的代码:
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);
}
}
使用此代码会在 grid.add(new int[n])
处抛出一个 NullPointerException
。如何将数据添加到 grid
?
最佳答案
您还没有初始化ArrayList
。
ArrayList<int[]> grid = new ArrayList<>();
关于java - 向 ArrayList 添加元素时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43270299/