給定一個長度呐馆,隨機產(chǎn)生一個該長度的字符串,由大寫莲兢,小寫字母以及數(shù)字組成?
Java中隨機數(shù)的生成:?
java.util.Random r = new java.util.Random();
int a = r.nexInt(100); a 0-99的隨機數(shù)
這里有多種做法
第一種 StringBuilder
```
public class Demo11{
public static void main(String[] args) {
System.out.println("請輸入長度");
print(randomStr(new Scanner(System.in).nextInt()));
}
public static StringBuilder randomStr(int len) {
// 存儲
StringBuilder sBuilder1 = new StringBuilder();
if(len <= 0) {
return sBuilder1;
}
// 思路: 使用StringBuilder將a-zA-Z0-9裝起,再用隨機數(shù)
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("abcdefghijklmnopqrstuvwxyz0123456789");
// 創(chuàng)建隨機數(shù)類對象
Random random = new Random();
// 使用整形隨機數(shù)
for (int i = 0; i < len; i++) {
char schar = sBuilder.charAt(random.nextInt(sBuilder.length()));
sBuilder1.append(schar);
}
return sBuilder1;
}
public static void print(StringBuilder stringBuilder) {
System.out.println(stringBuilder);
}
}
```
這種做法利用到了StringBuilder的特性
第二種做法:
```
public static void randomStr2(int len) {
// 存儲
StringBuilder sBuilder1 = new StringBuilder();
//Math.random()* //0 - 1
int a = (int) ( Math.random () * 3 );// 生成0 - 3的隨機數(shù)也就是 0汹来,1续膳,2
for (int i = 0; i < len; i++) {
if(a == 0) {
// 0-9 數(shù)字 48-57
char str = ((char)(Math.random()*10+48));
System.out.println(str);
sBuilder1.append(str);
}else if(a == 1) {
// a-z 97-122
char str = ((char)(Math.random()*26+97)); //91
sBuilder1.append(str);
}else if(a == 2) {
// A-Z 65-90
char str = ((char)(Math.random()*26+65)); //91
sBuilder1.append(str);
}
}
System.out.println(sBuilder1);
}
```
分別利用 ASCLL碼值 對應的 a-z A-Z 0-9