题目来源:生成随机字符串 —— 每日一练第5天(Java语言)
题目详情
解题思路生成一个由大写字母和数字组成的6位随机字符串,并且字符串不重复
代码实现因为要组成随机的字符串,所以第一反应想到的是Math.random()函数,但是此函数,所能表示的范围是[0.0,1.0)
由大写字母和数字组成的字符串的话,一共就有A~Z和0~9共36个字符组成
也就是说,需要对Math.random()所表示的范围进行扩大。可以把[0.0,1.0)乘以36,再强转为int型,这样范围就落在[0,36)了。
然后再进行六次这样的操作即可组成一个6位的随机字符串了
public class RandomString {
public static void main(String[] args) {
Solution solution = new RandomString().new Solution();
// to test
char[] cs = new char[6];
cs = solution.generate();
for(int i = 0 ; i < cs.length ; i++) {
System.out.print(cs[i] + " ");
}
}
class Solution {
public char[] generate() {
char[] letters = { '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', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] chs = new char[6];
for(int i = 0 ; i < 6 ; i++) {
int index = (int)(Math.random()*letters.length);
chs[i] = letters[index];
}
return chs;
}
}
}



