这是我自己在网上整理的写的一个小demo:
package test;
import java.util.Random;
public class Test {
public static void main(String[] args) {
// creatPaswd();
String val = getCharAndNumr();
System.out.println("生成的随机数:"+val);
System.exit(0);
}
/**
* 生成随机数方法这里不传参数默认是6位数
* @return
*/
public static String getCharAndNumr()
{
String val = "";
Random random = new Random();
for(int i = 0; i < 6; i++)//循环6次生成6位
{
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));
}
}
return val;
}
// private static void creatPaswd() {
// Random random = new Random();
// StringBuffer sb = new StringBuffer();
// for (int i = 0; i < 6; i++) {
// int number = random.nextInt(9);
// sb.append(number);
// }
// System.out.println(sb.toString());
//
// }
}
仅此拜笔以闻!