有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java生成必须包含字母、数字和特殊字符(610位)的随机字符串

我正在生成一个6到10位数的密码

这是我的密码,给我6-10位的随机密码

val AB = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789:<=>?@_!#%&()*+,-.~";
val rnd = new Random();

def randomPassword(): String = {
    val len = rnd.nextInt(5) + 5
    val sb = new StringBuilder(len);
    for (i <- 0 to len)
       sb.append(AB.charAt(rnd.nextInt(AB.length())));
    return sb.toString();
    }

它工作正常,但问题是,有时它会给出所有的数字或字母

我每次都想要字母、数字和特殊字符的组合。有什么建议吗


共 (5) 个答案

  1. # 1 楼答案

    下面是一个更惯用的解决方案,它提供了更好的API

    object password {
      import scala.util.Random
      import scala.collection.immutable.Stream
    
    
      private def gen = Random.alphanumeric
    
      def get(len: Int): String = {    
        def build(acc: String, s: Stream[Char]): String = {
          if (s.isEmpty) acc
          else build(acc + s.head, s.tail)
        }
    
        build("", gen take len)
      }
    }
    

    让我们生成一些密码

    1 to 25 foreach { _ => println(password get 8) }
    

    你会看到类似的东西

    YBk2UrOV
    GD4eLexS
    l8yxAkp9
    ooQnaRpd
    NgHAruB8
    pMXpi4ad
    

    注意:此解决方案可以进行几轮优化。例如@tailrecStringBuilder

  2. # 2 楼答案

    首先生成所有字母的随机密码,然后根据需要将部分字母替换为数字/特殊字符

    (顺便说一句,我不熟悉Scala,所以我将使用Java的语法,因为我不知道键入的内容是否有效。很抱歉。)

    // Split source string into letters, numbers, and specials
    String AB = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    String numbers = "0123456789";
    String specials = ":<=>?@_!#%&()*+,-.~";
    
    String randomPassword() {
        StringBuilder sb = new StringBuilder();
        int len = rnd.nextInt(5) + 5;
    
        // Generate password with letters first. This part is the same as the original code.
        for (int i = 0; i <= len; i++) {
             sb.append(AB.charAt(rnd.nextInt(AB.length())));
        }
    
    
        // Generate an index to replace with a number
        int numberIndex = rnd.nextInt(len);
        // Generate an index to replace with a special character
        int specialIndex;
        do {
            specialIndex = rnd.nextInt(len);
        } while (specialIndex == numberIndex);
        // Replace one letter with a number
        sb.setCharAt(numberIndex, numbers.charAt(rnd.nextInt(numbers.length())));
        // Replace one letter (or the number if you're unlucky) with a special character
        sb.setCharAt(specialIndex, specials.charAt(rnd.nextInt(specials.length())));
    }
    

    这是一个开始,有一个缺陷(只有一个数字+特殊字符),但很容易修复。如果一个密码不满足您的条件,此解决方案也比生成全新密码更有效,并且您可以保证在方法返回时获得一个有效的密码

  3. # 3 楼答案

    def randomPassword(): String = {
        val len = rnd.nextInt(5) + 5
        val sb = new StringBuilder(len);
        for (i <- 0 to len)
           sb.append(AB.charAt(rnd.nextInt(AB.length())));
    
        if(sb.toString is allString or allNum){
           return randomPassword();
        }
        return sb.toString();
        }
    
  4. # 4 楼答案

    使用不可变数据结构对scala来说更为惯用。下面的代码可以工作

      protected def nextChar(): Char = Random.nextPrintableChar()
    
      def randomString(length: Int = 10): String = {
        (0 until length).map(_ => nextChar()).mkString
      }
    

    编辑: 为了确保字符串中始终有数字、特殊字符和字母表,我将分别生成每一类字母,然后以函数方式或简单地使用Random随机连接它们。洗牌(字符列表)。mkString=D

  5. # 5 楼答案

    您可以应用while循环的原理

    1. 将附加的密码存储到变量中
    2. 使用while循环检查密码是否不包含数字和/或符号,如果不包含,请再次重新生成密码并将其存储到变量中
    3. 当while循环自动中断时,返回变量