用Java编写生成具有严格限制的随机字符串的算法

5
我正在尝试制作一个程序,为用户生成随机的帐户名。用户将点击按钮,并将帐户名复制到剪贴板中。GUI部分已经工作正常,但我无法想出处理字符串随机生成的最佳方法。

用户名中允许使用的字符:A-Z a-z _

不能包含数字、其他符号和连续两个相同的字符。

必须是六位长度。

我的想法:

create an array of characters:

[ _, a, b, c, d ... etc ]

Generate a random integer between 0 and array.length - 1
 and pick the letter in that slot.

Check the last character to be added into the output String, 
and if it's the same as the one we just picked, pick again.

Otherwise, add it to the end of our String.

Stop if the String length is of length six.

有没有更好的方法?也许可以使用正则表达式?我觉得我现在想做的方式可能很糟糕。


1
只是为了明确,a_a_a_可以吗? - user1803551
为什么需要更好的方法?你的想法有什么问题吗?它很简单,适合你的要求 - 只需要编码即可。 - user3707125
2
请注意,您可能忘记了一个重要的限制:您不能有两个用户名相同的用户,对吧?为什么不让用户选择自己的名字,这样他们就可以记住呢?准备好接受那些忘记账户名的用户的不断请求吧。 - JB Nizet
1个回答

3

我认为你提出的算法没有什么问题(除了需要处理添加的第一个字符,而不是检查你是否已经添加它)。你可以将其提取到一个static方法中,并使用Random,例如:

static Random rand = new Random();

static String getPassword(String alphabet, int len) {
  StringBuilder sb = new StringBuilder(len);
  while (sb.length() < len) {
    char ch = alphabet.charAt(rand.nextInt(alphabet.length()));
    if (sb.length() > 0) {
      if (sb.charAt(sb.length() - 1) != ch) {
        sb.append(ch);
      }
    } else {
      sb.append(ch);
    }
  }
  return sb.toString();
}

然后您可以使用类似以下的方式调用它:
public static void main(String[] args) {
  StringBuilder alphabet = new StringBuilder();
  for (char ch = 'a'; ch <= 'z'; ch++) {
    alphabet.append(ch);
  }
  alphabet.append(alphabet.toString().toUpperCase()).append('_');
  String pass = getPassword(alphabet.toString(), 6);
  System.out.println(pass);
}

好主意,使用StringBuilder。我忘记了它的存在。谢谢! - Hatefiend

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接