1

My code:

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);
    }
}

Using this code throws a NullPointerException at grid.add(new int[n]). How can I add data to grid?

0

3 Answers 3

3

You haven't initialize the ArrayList.

ArrayList<int[]> grid = new ArrayList<>();
Sign up to request clarification or add additional context in comments.

Comments

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);
 }
}

Comments

0

Without initialization you can not add element in list.

And you can also pass another ArrayList in <> e.g.:

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

Because it is much dynamic.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.