加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-15 01:04:39 所属栏目:Java 来源:网络整理
导读:我正在尝试制作一个程序来为用户生成一个随机帐户名.用户将点击一个按钮,它会将帐户名称复制到他的剪贴板.它的GUI部分正在工作,但我想不出处理随机生成String的最佳方法. 用户名中允许的字符:A-Z a-z _ 连续数字,没有其他符号和两个相同的字符都不会出现.

我正在尝试制作一个程序来为用户生成一个随机帐户名.用户将点击一个按钮,它会将帐户名称复制到他的剪贴板.它的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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读