隨筆-199  評論-203  文章-11  trackbacks-0
          //根據不同的難度產生隨機字母和數字
          for(int i=0; readomNumStart.length()<4; i++) {
          if(difficult == 1) {

          //產生隨機的0-9的數字
          a = String.valueOf((int)(Math.random() * 10)) ;
          }
          if(difficult == 2) {

          //在0-9和a,b,c,d中隨機產生。
          String[] readomWord = {"0","1","2","3","4","5","6","7","8","9","a","b","c","d"};
          int readomWordIndex = (int)(Math.random() * 13);
          a = readomWord[readomWordIndex];
          }
          if(difficult == 3) {

          //產生隨機的字母
          char readomLetter = (char)(Math.random ()*26+'a');
          a = String.valueOf(readomLetter) ;
          }
          if(difficult == 4) {

          //產生隨機的數字和字母的組合
          String[] readomHard = new String[20];
          int readomWordIndex = (int)(Math.random() * 19);
          for(int j=0; j<20; j++) {
          int readomWordNum = (int)(Math.random() * 10);
          char readomLetter = (char)(Math.random ()*26+'a');
          if(readomWordNum % 2 == 0) {
          readomHard[j] = readomWordNum + "";
          }else{
          readomHard[j] = String.valueOf(readomLetter);
          }
          }
          a = readomHard[readomWordIndex];
          }

          //

              這樣寫代碼比較短。我也參考了許多人的代碼大部分都很復雜。我不喜歡寫那么多代碼,所以就這樣寫了。還不能知道這樣寫效率有沒有問題,在我本機上運行沒有什么感覺。

          posted on 2009-04-07 08:09 Werther 閱讀(3356) 評論(2)  編輯  收藏 所屬分類: 10.Java

          評論:
          # re: Java產生隨機數代碼 2009-04-07 11:54 | aisdf
          char[] numbersAndLetters = ("0123456789" + "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
          char[] randBuffer = new char[length];
          for (int i = 0; i < randBuffer.length; i++) {
          randBuffer[i] = numbersAndLetters[randGen.nextInt(numbersAndLetters.length)];
          }
          return new String(randBuffer);

          比你短  回復  更多評論
            
          # re: Java產生隨機數代碼 2009-04-09 00:08 | 黑蝙蝠
          頂一下~~~:)  回復  更多評論
            
          主站蜘蛛池模板: 北宁市| 津南区| 鹤壁市| 荃湾区| 青川县| 南华县| 方山县| 滨州市| 九龙坡区| 乌兰县| 绿春县| 左云县| 东乌| 商南县| 沐川县| 铜鼓县| 宁德市| 牡丹江市| 玉龙| 来宾市| 安泽县| 华池县| 咸宁市| 库伦旗| 蓝山县| 林西县| 兖州市| 宽甸| 龙游县| 西充县| 乌拉特前旗| 定兴县| 惠州市| 米林县| 马公市| 禄劝| 民丰县| 台湾省| 台州市| 淳安县| 永清县|