Java Collection How to - Populate a 2d array with random alphabetic values from a range








Question

We would like to know how to populate a 2d array with random alphabetic values from a range.

Answer

import java.util.Arrays;
import java.util.Random;
/*from ww w.  j  a v  a  2  s. c  om*/
public class Main {
  public static void main(String[] args) {
    char array[][] = new char[5][5];
    Random rnd = new Random();
    for (int i = 0; i < 5; i++) {
      for (int j = 0; j < 5; j++) {
        int x = rnd.nextInt(5); // 0 to 4
        switch (x) {
        case 0: {
          array[i][j] = 'a';
          break;
        }
        case 1: {
          array[i][j] = 'b';
          break;
        }
        case 2: {
          array[i][j] = 'c';
          break;
        }
        case 3: {
          array[i][j] = 'd';
          break;
        }
        case 4: {
          array[i][j] = 'e';
          break;
        }
        }
      }
    }
    System.out.println(Arrays.deepToString(array));
  }
}

The code above generates the following result.