com.neusoft.mid.clwapi.tools.RandomNumberUtil.java Source code

Java tutorial

Introduction

Here is the source code for com.neusoft.mid.clwapi.tools.RandomNumberUtil.java

Source

/*******************************************************************************
 * @(#)RandomNumberUtil.java 2011-8-20
 *
 * Copyright 2011 Neusoft Group Ltd. All rights reserved.
 * Neusoft PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *******************************************************************************/
package com.neusoft.mid.clwapi.tools;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.math.RandomUtils;

/**
 * @author <a href="mailto:majch@neusoft.com">majch</a>
 * @version $Revision 1.0 $ 2011-8-20 ?12:14:28
 */
public class RandomNumberUtil {

    private static final int[] prefix = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    /**
     * ?18?long?(long?9223372036854775807,19?)
     * 
     * @param digit
     *            ???
     */
    public static long randomLong(final int digit) {
        if (digit >= 19 || digit <= 0) {
            throw new IllegalArgumentException("digit should between 1 and 18(1<=digit<=18)");
        }
        final String s = RandomStringUtils.randomNumeric(digit - 1);
        return Long.parseLong(getPrefix() + s);
    }

    public static String randomString(final int digit) {
        if (digit >= 19 || digit <= 0) {
            throw new IllegalArgumentException("digit should between 1 and 18(1<=digit<=18)");
        }
        return getPrefix() + RandomStringUtils.randomNumeric(digit - 1);
    }

    /**
     * ??long?,?,minDigit<=maxDigit
     * 
     * @param minDigit
     *            ???? minDigit>=1
     * @param maxDigit
     *            ??? maxDigit<=18
     */
    public static long randomLong(final int minDigit, final int maxDigit) {
        if (minDigit > maxDigit) {
            throw new IllegalArgumentException("minDigit > maxDigit");
        }
        if (minDigit <= 0 || maxDigit >= 19) {
            throw new IllegalArgumentException("minDigit <=0 || maxDigit>=19");
        }
        return randomLong(minDigit + getDigit(maxDigit - minDigit));
    }

    private static int getDigit(final int max) {
        return RandomUtils.nextInt(max + 1);
    }

    /**
     * ????
     * 
     * @return
     */
    private static String getPrefix() {
        return prefix[RandomUtils.nextInt(9)] + "";
    }

    public static void main(final String[] aa) {

        for (int i = 0; i < 100; i++) {
            System.out.println(RandomNumberUtil.randomString(10));
        }
    }
}