题目:
定义一个方法,获取长度为5的字符串,字符串由4个随机的大小写字母和1个阿拉伯数字组成,英文字母和数字的顺序是随机的。
分析:
1.把所有大小写字母存放到一个字符数组char1里,随机取出5个存放到另一个字符数组char2中。
2.char2随机取出一个索引位置的字母,替换成数字。
代码:
package com.heima.demo1;
import java.util.Random;
/*
第三题:分析以下需求,并用代码实现
定义String getStr()方法
功能描述:
获取长度为5的随机字符串
字符串由随机的4个大小写英文字母和1个0-9之间(包含0和9)的整数组成
英文字母和数字的顺序是随机的
*/
public class Work2 {
public static void main(String[] args) {
char[] ch2=Test01();
char[] ch3=new char[5];
//根据索引随机取出ch2中的字符,存放到新的字符数组ch3中,现在ch3中存放的是5个字母
Random random=new Random();
for(int i=0;i<ch3.length;i++){
char char1=ch2[random.nextInt(ch2.length)];
ch3[i]=char1;
}
//随机取出一个字母替换成数字
int index=random.nextInt(ch3.length);
int num=random.nextInt(9)+48;
ch3[index]=(char)num;
System.out.println(ch3);
}
public static char[] Test01(){
//先把大小写英文字母和数字存储到字符数组里,再随机取出5个字符
char[] ch1=new char[52];
int count=0;
for(char c='A'; c<='Z';c++){
ch1[count++]=c;
}
for(char c='a'; c<='z';c++){
ch1[count++]=c;
}
return ch1;
}
}
输出结果:
BZBs7
Process finished with exit code 0