0

I have a 2D array. I assign it likt this int populations[][] = new int [300][1];. I would like to assign 1 random value (from 0 - 4) into the each row of 300. This what I got so far.

 private void test(){

    for (int i = 0; i < 300; i++){

        for(int j = 0; j < 1; j++){

            populations[i][j] = random.nextInt(4);

       }
    }

    System.out.println(populations.length);
    System.out.println(Arrays.deepToString(populations));
}

However, I got an Array Index out of Bounds Exception of 300. How could I fix that?

kings077712
  • 55
  • 11

1 Answers1

1

Are you sure? This program runs without error...

import java.util.Arrays;
import java.util.Random;

public class Rnd {

    public static void main(String[] args) {
        Random random = new Random();
        int[][] populations = new int[300][1];

        for(int i = 0; i < 300; i++) {
            for(int j = 0; j < 1; j++) {
                populations[i][j] = random.nextInt(4);
            }
        }

        System.out.println(Arrays.toString(populations));
    }
}
BretC
  • 4,141
  • 13
  • 22