问题描述
- java 生成随机的6位字符 包括a-z A-Z 0-9
-
java 生成随机的6位字符 包括a-z A-Z 0-9
解决方案
public static void main(String[] args) {
String a = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] rands = new char[6];
for (int i = 0; i < rands.length; i++)
{
int rand = (int) (Math.random() * a.length());
rands[i] = a.charAt(rand);
}
for(int i=0;i<rands.length;i++){
System.out.println(rands[i]);
}
}
解决方案二:
String s = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
Random r = new Random();
String result;
for (int i =0; i < 6; i++ )
{
int n = r.nextInt(62);
result += s.subString(n, 1);
}
result就是你要的。
解决方案三:
定义一个62位长的数组存放这些字母数字,用随机函数随机生成一个整数,限制范围0到61,(自己看随机函数的api)
6次随机结果连接赋给一个字符串就行。
想要细致的分化,可以设置3个数组分别存放大小写字母及数字,这样你可以控制随机数产生的规则。
解决方案四:
再搞个hashset 把n放进去判断是否重样 可以搞出不重样的六位字符
解决方案五:
public String randSix(){
String []baseStr = {"1","2","3","4","5","6","7","8","9","0",
"a","b","c","d","e","A","B"};
String str="";
for(int i = 0 ;i<6;i++){
int index = ((int)(100*Math.random()))%baseStr.length;
System.out.println(index);
str += baseStr[index];
}
return str;
}
这个可以自己定义想要输出的字符串包含哪些,特殊符号都可以
解决方案六:
如果还包括汉字的话就需要Unicode编码了,用法和他们写的类似,你可以百度下。
解决方案七:
随机生成
希望对你有用
解决方案八:
public static String generateWord(int digits,boolean onlyNumber) {
String[] beforeShuffle = null;
if(onlyNumber){
beforeShuffle = new String[] { "0","1","2", "3", "4", "5", "6", "7",
"8", "9"};
}else{
beforeShuffle = new String[] { "0","1","2", "3", "4", "5", "6", "7",
"8", "9", "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" };
}
List list = null;
if(beforeShuffle.length
list = new ArrayList(Arrays.asList(beforeShuffle));
while(list.size()<digits){
list.addAll(Arrays.asList(beforeShuffle));
}
}else{
list = Arrays.asList(beforeShuffle);
}
Collections.shuffle(list);
StringBuilder sb = new StringBuilder(digits);
for (int i = digits-1; i>=0; i--) {
sb.append(list.get(i));
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(generateWord(6, true));
}
解决方案九:
网上有很多现成的代码啊
package com.yuchao.javadoc;
/**
- 生成6位的随机字符串
- @author Jack.yu
- */
public class SixNumberRadom {
/**
- @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String result="";
for(int i=0;i<6;i++){
int intVal=(int)(Math.random()*26+97);
result=result+(char)intVal;
}
System.out.print(result);
}
- @param args
}
解决方案十:
http://blog.csdn.net/baidu_25310663/article/details/45243853
java生成随机不重复id