public static String generateString(Random rng, String characters, int length)
{
char[] text = new char[length];
for (int i = 0; i < length; i++)
{
text[i] = characters.charAt(rng.nextInt(characters.length()));
}
return new String(text);
}
现在,如果你确实需要它是随机的,我们首先注意到一个生成的数字序列,不包含重复不能被称为随机。: p 现在我们已经完成了这个步骤,最快的方法是使用一个包含已经生成的所有 ID 的 Hashtable或 HashMap。无论何时生成一个新 ID,都要根据散列表检查它,如果 ID 已经出现,则重新生成。如果学生的数量远远小于 ID 的范围,这通常会很好地工作。如果没有,那么随着需要重新生成 ID 的可能性增加,您将陷入更深的麻烦中,P (生成新 ID) = number _ of _ ID _ already _ generated/number _ of _ all _ may _ ids。在这种情况下,请检查第一段(您需要 ID 是随机的吗?).
public class RandomNumberGenerator {
private static final Set<String> generatedNumbers = new HashSet<String>();
public RandomNumberGenerator() {
}
public static void main(String[] args) {
final int maxLength = 7;
final int maxTry = 10;
for (int i = 0; i < 10; i++) {
System.out.println(i + ". studentId=" + RandomNumberGenerator.getRandomId(maxLength, maxTry));
}
}
public static String getRandomId(final int maxLength, final int maxTry) {
final Random random = new Random(System.nanoTime());
final int max = (int) Math.pow(10, maxLength);
final int maxMin = (int) Math.pow(10, maxLength-1);
int i = 0;
boolean unique = false;
int randomId = -1;
while (i < maxTry) {
randomId = random.nextInt(max - maxMin - 1) + maxMin;
synchronized (generatedNumbers) {
if (generatedNumbers.contains(randomId) == false) {
unique = true;
break;
}
}
i++;
}
if (unique == false) {
throw new RuntimeException("Cannot generate unique id!");
}
synchronized (generatedNumbers) {
generatedNumbers.add(String.valueOf(randomId));
}
return String.valueOf(randomId);
}
}
Random ran = new Random();
int top = 3;
char data = ' ';
String dat = "";
for (int i=0; i<=top; i++) {
data = (char)(ran.nextInt(25)+97);
dat = data + dat;
}
System.out.println(dat);