Instance code of random generation of mobile phone short message verification code based on Java

  • 2021-07-16 02:35:19
  • OfStack

Simple version


/**   *  Produce 4 Bit random number (0000-9999)
   *
   * @return 4 Bit random number 
   */
  public static String getFourRandom() {
    return StringUtils.leftPad(new Random().nextInt(10000) + "", 4, "0");
  }

Complex version


/**
   *  Creates a specified number of random strings 
   * @param numberFlag  Is it a number 
   * @param length
   * @return
   */
  public static String createRandom(boolean numberFlag, int length){
    String retStr = "";
    String strTable = numberFlag ? "1234567890" : "1234567890abcdefghijkmnpqrstuvwxyz";
    int len = strTable.length();
    boolean bDone = true;
    do {
      retStr = "";
      int count = 0;
      for (int i = 0; i < length; i++) {
        double dblR = Math.random() * len;
        int intR = (int) Math.floor(dblR);
        char c = strTable.charAt(intR);
        if (('0' <= c) && (c <= '9')) {
          count++;
        }
        retStr += strTable.charAt(intR);
      }
      if (count >= 2) {
        bDone = false;
      }
    } while (bDone);
    return retStr;
  }

Summarize

The above is the site to introduce to you based on Java random generation of mobile phone SMS verification code example code, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!


Related articles: