本文實例為大家分享了java生成隨機字符串的具體代碼,供大家參考,具體內容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
import java.util.Random; public class CharacterUtils { //方法1:length為產生的位數 public static String getRandomString( int length){ //定義一個字符串(A-Z,a-z,0-9)即62位; String str= "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890" ; //由Random生成隨機數 Random random= new Random(); StringBuffer sb= new StringBuffer(); //長度為幾就循環幾次 for ( int i= 0 ; i<length; ++i){ //產生0-61的數字 int number=random.nextInt( 62 ); //將產生的數字通過length次承載到sb中 sb.append(str.charAt(number)); } //將承載的字符轉換成字符串 return sb.toString(); } /** * 第二種方法 */ public static String getRandomString2( int length){ //產生隨機數 Random random= new Random(); StringBuffer sb= new StringBuffer(); //循環length次 for ( int i= 0 ; i<length; i++){ //產生0-2個隨機數,既與a-z,A-Z,0-9三種可能 int number=random.nextInt( 3 ); long result= 0 ; switch (number){ //如果number產生的是數字0; case 0 : //產生A-Z的ASCII碼 result=Math.round(Math.random()* 25 + 65 ); //將ASCII碼轉換成字符 sb.append(String.valueOf(( char )result)); break ; case 1 : //產生a-z的ASCII碼 result=Math.round(Math.random()* 25 + 97 ); sb.append(String.valueOf(( char )result)); break ; case 2 : //產生0-9的數字 sb.append(String.valueOf ( new Random().nextInt( 10 ))); break ; } } return sb.toString(); } public static void main(String[] args) { System.out.println(CharacterUtils.getRandomString( 12 )); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/ipetergo/p/7636982.html