Java Random Char randomChars(char[] alphabet, int length)

Here you can find the source of randomChars(char[] alphabet, int length)

Description

random Chars

License

Apache License

Declaration

public static char[] randomChars(char[] alphabet, int length) throws IllegalArgumentException 

Method Source Code

//package com.java2s;
/**   /*from   www.  j a v  a2  s.c  om*/
 * Copyright 2011 The Buzz Media, LLC
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.Random;

public class Main {
    public static final char[] EMPTY_CHARS = new char[0];
    private static final Random RANDOM = new Random(System.currentTimeMillis());

    public static char[] randomChars(char[] alphabet, int length) throws IllegalArgumentException {
        if (alphabet == null || alphabet.length == 0)
            throw new IllegalArgumentException(
                    "alphabet cannot be null or empty, it must contain a valid list of characters to pull values from. Many complete alpha, numeric and symbolic alphabets are pre-defined by this class for ease of use.");
        if (length < 0)
            throw new IllegalArgumentException("length must be >= 0");
        if (length == 0)
            return EMPTY_CHARS;

        int max = alphabet.length - 1;
        char[] result = new char[length];

        for (int i = 0; i < result.length; i++)
            result[i] = alphabet[randomInt(max)];

        return result;
    }

    public static int randomInt(int max) throws IllegalArgumentException {
        return randomInt(0, max);
    }

    public static int randomInt(int min, int max) throws IllegalArgumentException {
        if (min < 0 || max < 0 || min > max)
            throw new IllegalArgumentException(
                    "min [" + min + "] must be >= 0, max [" + max + "] must be >= 0 and >= min.");

        double d = RANDOM.nextDouble();
        return (int) (d * (double) (max - min) + min);
    }
}

Related

  1. randomChar()
  2. randomChar()
  3. randomChar(char[] letters)
  4. randomChar(Random r)
  5. randomCharacter(boolean includeSymbols)