JAVA生成随机字符串方法
生活随笔
收集整理的這篇文章主要介紹了
JAVA生成随机字符串方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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) {for(int i=1;i<=25;i++) { System.out.println(CharacterUtils.getRandomString(9));}}
}
?
總結
以上是生活随笔為你收集整理的JAVA生成随机字符串方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: TestSMS
- 下一篇: 动态添加行 为元素解绑事件 delega