Java Collection How to - Fill an array with randomly chosen characters from a different array








Question

We would like to know how to fill an array with randomly chosen characters from a different array.

Answer

/* w w w  .j  a  v a2 s.c o m*/
public class Main {

  public static void main(String[] args) {
    char[] anArray = { '!', '@', '#', '$', '%', '^', '&', '*', '+', '=', '~',
        '<', '>', '?' };
    int passwordLength = 20, symbolCount = 9;

    while (symbolCount > anArray.length) {
      symbolCount = (anArray.length - 1);
    }
    char[] patternArray = new char[passwordLength];

    int srcIndex = 0;
    for (int j = 0; j < passwordLength; j++) {
      patternArray[j] = anArray[srcIndex];
      srcIndex++;
      if (srcIndex > (anArray.length - 1))
        srcIndex = 0;
    }
    System.out.print(patternArray);
  }
}

The code above generates the following result.