Java Random Number getRandomNumber(int len)

Here you can find the source of getRandomNumber(int len)

Description

return a len not repeat random number String, len must be less than 10

License

Apache License

Parameter

Parameter Description
len must less than 10

Return

random number

Declaration

public static String getRandomNumber(int len) 

Method Source Code

//package com.java2s;
/*// ww  w  .  j a  va2s. c  o m
 * Copyright 2014 the original author or authors.
 *
 * 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 {
    /**
     * return a <code>len</code> not repeat random number String, len must be
     * less than 10
     *
     * @param len must less than 10
     * @return random number
     */
    public static String getRandomNumber(int len) {
        StringBuilder sb = new StringBuilder();
        String str = "0123456789";
        Random r = new Random();
        for (int i = 0; i < len; i++) {
            int num = r.nextInt(str.length());
            sb.append(str.charAt(num));
            str = str.replace((str.charAt(num) + ""), "");
        }
        return sb.toString();
    }
}

Related

  1. getRandomNumber(final int from, final int to)
  2. getRandomNumber(final int maxInt, final int minInt)
  3. getRandomNumber(int bit)
  4. getRandomNumber(int bound)
  5. getRandomNumber(int digit)
  6. getRandomNumber(int len)
  7. getRandomNumber(int length)
  8. getRandomNumber(int length)
  9. getRandomNumber(int length)