Creates random string that consist only of numbers. - Java java.util

Java examples for java.util:Random String

Description

Creates random string that consist only of numbers.

Demo Code


import java.util.Random;

public class Main{
    protected static final Random rnd = new Random();
    /**//from   ww w .j ava2  s .  c  om
     * Creates random string that consist only of numbers.
     */
    public static String randomNumeric(int count) {
        return random(count, '0', '9');
    }
    /**
     * Creates random string whose length is the number of characters specified.
     * Characters are chosen from the set of characters specified.
     */
    public static String random(int count, char[] chars) {
        if (count == 0 || chars == null) {
            return StringUtil.EMPTY_STRING;
        }
        char[] result = new char[count];
        while (count-- > 0) {
            result[count] = chars[rnd.nextInt(chars.length)];
        }
        return new String(result);
    }
    /**
     * Creates random string whose length is the number of characters specified.
     * Characters are chosen from the set of characters specified.
     */
    public static String random(int count, String chars) {
        if (chars == null) {
            return StringUtil.EMPTY_STRING;
        }
        return random(count, chars.toCharArray());
    }
    /**
     * Creates random string whose length is the number of characters specified.
     * Characters are chosen from the provided range.
     */
    public static String random(int count, char start, char end) {
        if (count == 0) {
            return StringUtil.EMPTY_STRING;
        }
        char[] result = new char[count];
        int len = end - start + 1;
        while (count-- > 0) {
            result[count] = (char) (rnd.nextInt(len) + start);
        }
        return new String(result);
    }
}

Related Tutorials