说到这里就不得不提一下Java的生成随机数的函数了;
/**
* 随机数
*/
public class RandomDemo01 {
public static void main(String[] args) {
//创建随机数对象
Random ran = new Random(System.currentTimeMillis());
for(int i=0;i<10;i++){
int t = ran.nextInt(10);//[0,10);
System.out.println(t);
}
}
}
这就是随机生成的10个随机数。
不妨动动咱们聪明的小脑瓜,结合上一篇文章汉字的编码范围,咱们随机生成4个字的汉字验证码
*
* 汉字验证码的简易实现
*/
public class RandomDemo02 {
public static <bool> void main(String[] args) {
//创建随机对象
Random ran = new Random(System.currentTimeMillis());
//创建输入对象
Scanner input = new Scanner(System.in);
//规定产生随机数的范围
char min = '\u4e00';
char max = '\u9fa5';
//规定产生4个随机汉字
boolean f = true;
while(f) {
String str = "";
for (int i = 0; i < 4; i++) {
int t = ran.nextInt(max - min) + min;//[min,max);
str += (char)t;
}
System.out.println(str);
System.out.print("是否重新生成(y/n):");
String line = input.nextLine();
if ("n".equals(line)) {
f=false;
}
}
System.out.println("谢谢使用!");
}
}