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

我正在尝试制作一个程序来为用户生成一个随机帐户名.用户将点击一个按钮,它会将帐户名称复制到他的剪贴板.它的GUI部分正在工作,但我想不出处理随机生成String的最佳方法.

用户名中允许的字符: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.

有没有更好的办法?也许正则表达式?我有一种感觉,我想这样做的方式非常糟糕.

最佳答案
我没有看到你提出的算法有什么问题(除了你需要处理你添加的第一个字符而不检查你是否已经添加它).您也可以将其提取为静态方法并使用随机类似,

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);
}

相关文章

摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠...
今天犯了个错:“接口变动,伤筋动骨,除非你确定只有你一个...
Writer :BYSocket(泥沙砖瓦浆木匠)微 博:BYSocket豆 瓣:...
本文目录 线程与多线程 线程的运行与创建 线程的状态 1 线程...