您的位置:首页 > 编程语言 > Java开发

【Java】利用Math.Random()方法随机出四个字符的字符串,字符包括数字,大小写英文字母

2017-04-05 00:34 716 查看
问题

定义一个类,该类有方法:能随机一个有4个字符的字符串,其中 每个字符都是随机的数字或大小写字母(类似网站的验证)

在main方法中new该类,并调用他的方法随机10个字符串存放数组中。

工具

Eclipse

java编程语言

代码

import java.util.Arrays;

public class Test {
public static void main(String[] args) {
MyMethod mm=new MyMethod();
System.out.println("随机的验证码为:"+mm.MyMethod1());
String method1[]=new String[10];
for(int i=0;i<10;i++){
method1[i]=mm.MyMethod1();
}
System.out.println("随机十个验证码放入数组中:"+Arrays.toString(method1));
}
}

class MyMethod{

public String MyMethod1(){//能随机一个有4个字符的字符串,其中 每个字符都是随机的数字或大小写字母(类似网站的验证)
String str="";
for(int i=0;i<4;i++){
int n=(int) (Math.random()*3);
char c=' ';
if(n==0){
c=(char)(Math.random()*10+48);//随机出0-9个数字
}else if(n==1){
c=(char)(Math.random()*26+97);//随机出小写字母
}else{
c=(char)(Math.random()*26+65);//随机出大写字母
}
str=c+str; }
return str;}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 编程语言
相关文章推荐