本文實(shí)例為大家分享了java生成隨機(jī)字符串的具體代碼,供大家參考,具體內(nèi)容如下
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為產(chǎn)生的位數(shù) public static String getRandomString( int length){ //定義一個(gè)字符串(A-Z,a-z,0-9)即62位; String str= "zxcvbnmlkjhgfdsaqwertyuiopQWERTYUIOPASDFGHJKLZXCVBNM1234567890" ; //由Random生成隨機(jī)數(shù) Random random= new Random(); StringBuffer sb= new StringBuffer(); //長(zhǎng)度為幾就循環(huán)幾次 for ( int i= 0 ; i<length; ++i){ //產(chǎn)生0-61的數(shù)字 int number=random.nextInt( 62 ); //將產(chǎn)生的數(shù)字通過length次承載到sb中 sb.append(str.charAt(number)); } //將承載的字符轉(zhuǎn)換成字符串 return sb.toString(); } /** * 第二種方法 */ public static String getRandomString2( int length){ //產(chǎn)生隨機(jī)數(shù) Random random= new Random(); StringBuffer sb= new StringBuffer(); //循環(huán)length次 for ( int i= 0 ; i<length; i++){ //產(chǎn)生0-2個(gè)隨機(jī)數(shù),既與a-z,A-Z,0-9三種可能 int number=random.nextInt( 3 ); long result= 0 ; switch (number){ //如果number產(chǎn)生的是數(shù)字0; case 0 : //產(chǎn)生A-Z的ASCII碼 result=Math.round(Math.random()* 25 + 65 ); //將ASCII碼轉(zhuǎn)換成字符 sb.append(String.valueOf(( char )result)); break ; case 1 : //產(chǎn)生a-z的ASCII碼 result=Math.round(Math.random()* 25 + 97 ); sb.append(String.valueOf(( char )result)); break ; case 2 : //產(chǎn)生0-9的數(shù)字 sb.append(String.valueOf ( new Random().nextInt( 10 ))); break ; } } return sb.toString(); } public static void main(String[] args) { System.out.println(CharacterUtils.getRandomString( 12 )); } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/ipetergo/p/7636982.html