生成隨機的字符類

@zgcwkj  2018年11月10日

分類:

代碼 其它 

Java 生成隨機的字符代碼

代碼如下:

/**
 * 生成隨機碼
 * 
 * @author zgcwkj
 * @since 2018-11-10
 */
public class RandomCode {
  private static String strType = "";

  /**
   * 生成隨機碼
   * 
   * @param digital 數字
   * @param character 字符
   * @param symbol 符號
   */
  public RandomCode(boolean digital, boolean character, boolean symbol) {
    // 數字
    if (digital) {
      strType = "1|2|3|4|5|6|7|8|9|0";
    }
    // 字符
    if (character) {
      if (strType != "")
        strType += "|";// 避免前面不選
      strType += "q|w|e|r|t|y|u|i|o|p|a|s|d|f|g|h|j|k|l|z|x|c|v|b|n|m";
    }
    // 符號
    if (symbol) {
      if (strType != "")
        strType += "|";// 避免前面不選
      strType += ",|.|/|;|'|[|]|{|}|;|<|>|?|!|@|#|$|%|^|&|*|(|)|_|-|+|=|~";
    }
    // 防止空字符
    if (strType.equals("")) {
      strType = "null";
    }
  }

  /**
   * 獲取隨機碼
   * 
   * @param length
   *            長度
   * @return
   */
  public static String getRandom(int length) {
    String strRandom = "";
    String[] zf = strType.split("\\|");
    Random random = new Random();
    for (int i = 0; i < length; i++) {
      int sjs = random.nextInt(zf.length);
      strRandom += zf[sjs];
    }
    return strRandom;
  }
}

使用方法:

方法A:

RandomCode randomCode = new RandomCode(true, true, false);
string code = randomCode.getRandom(10);

方法B:

string code = new RandomCode(true, true, false).getRandom(10);

關聯 C# 版的隨機類:C# 版
附件下載:RandomCode.java



評論已關閉

Top