随机产生制定产度数字+字母的字符串_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 随机产生制定产度数字+字母的字符串

随机产生制定产度数字+字母的字符串

 2011/12/28 17:55:36  andesya  http://andesya.iteye.com  我要评论(0)
  • 摘要:packagecom.faithbj.shop.util;importjava.util.Random;publicclassGeneratePresentCardID{publicsynchronizedstaticStringgetCharacterAndNumber(intlength){Stringval="";Randomrandom=newRandom();for(inti=0;i<length;i++){StringcharOrNum=random.nextInt(2
  • 标签:字符串
package com.faithbj.shop.util;

import java.util.Random;

public class GeneratePresentCardID {
public synchronized static String getCharacterAndNumber(int length) {
String val = "";

Random random = new Random();
for (int i = 0; i < length; i++) {
String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; // 输出字母还是数字

if ("char".equalsIgnoreCase(charOrNum)) // 字符串
{
int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写字母还是小写字母
val += (char) (choice + random.nextInt(26));
} else if ("num".equalsIgnoreCase(charOrNum)) // 数字
{
val += String.valueOf(random.nextInt(10));
}
}
System.out.println(val);
return val;
}

public static void main(String[] args) {
getCharacterAndNumber(20);
}
}
================================
UUID

public static void main(String[] args) {
        String s = UUID.randomUUID().toString();
        String st = s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24);
       
        System.out.println(st.substring(0, 20));
    }

=================================
public static String getRandomString(int length) {
if (length <= 0) {
return "";
}
char[] randomChar = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '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','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P',
'Q','R','S','T','U','V','W','X','Y','Z' };
Random random = new Random();
StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < length; i++) {
stringBuffer.append(randomChar[Math.abs(random.nextInt()) % randomChar.length]);
}
System.out.println(stringBuffer.toString());
return stringBuffer.toString();
}
发表评论
用户名: 匿名