Here you can find the source of getRandomNumber(int len)
len
not repeat random number String, len must be less than 10
Parameter | Description |
---|---|
len | must less than 10 |
public static String getRandomNumber(int len)
//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(); } }