创建一个长度是5的随机字符串,随机字符有可能是数字,大写字母或者小写字母。

import java.util.Random;

public class RandomString {
public static void main(String[] args) {
	String str="";
    Random r=new Random();     //创建Random对象
    for(int i=0;i<5;i++) {
    	
    		int type=r.nextInt(3); //随机生成0,1,2中的一个数,对应大写字母,小写字母,数字
    		if(type==0) {
                        //对照ASCII码以及随机数生成方法,随机生成大写字母
    			str+=(char)(r.nextInt(90-65+1)+65
    		}
    		else if(type==1){
                        //对照ASCII码以及随机数生成方法,随机生成小写字母
    			str+=(char)(r.nextInt(122-97+1)+97);
    		}
    		else if(type==2) {
                        //对照ASCII码以及随机数生成方法,随机生成数字
    			str+=r.nextInt(9-0+1)+0;
    		}
    	}
    
    System.out.println(str);
}
}

对随机数生成有疑惑的小伙伴可到:随机数生成方法学习

猜你喜欢

转载自blog.csdn.net/qq_44624536/article/details/113757371
今日推荐