要求:
获取长度为5的随机字符串,字符串由随机的4个大写英文字母和1个0-9之间(包含0和9)的整数组成
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
//(1)定义长度为26,元素值为26个大写英文字母的数组chs
char[] chs = new char[26];
for (int i = 0; i < chs.length; i++) {
chs[i] = (char)(i + 65);
}
//(2)传递数组chs调用getStr(char[] chs)方法,获取返回值,并在控制台打印返回值
System.out.println(getStr(chs));
}
//定义方法,获取长度为5的随机字符串,字符串由随机的4个大写英文字母和1个0-9之间(包含0和9)的整数组成
public static String getStr(char[] chs) {
Random r = new Random();
String s = new String(chs);
char[] arr = new char[5];
for (int i = 0; i < arr.length; i++) {
char c = (char)(r.nextInt(43) + 48);
if (s.indexOf(c) != -1) {
if (i != arr.length - 1) {
arr[i] = c;
}else {
int count = 0;
for (int j = 0; j < i; j++) {
if (arr[j] >= '0' && arr[j] <= '9') {
count++;
}
}
if (count == 0) {
i--;
}else {
arr[i] = c;
}
}
}else if (c >= '0' && c <= '9') {
int count = 0;
for (int j = 0; j < i; j++) {
if (arr[j] >= '0' && arr[j] <= '9') {
count++;
}
}
if (count == 0) {
arr[i] = c;
}else {
i--;
}
}else {
i--;
}
}
String s2 = new String(arr);
return s2;
}
}
|
|