「Java」Math.random()で指定文字列範囲のランダム文字列を生成する
構文
1.public static double random()
0.0以上で1.0より小さい、正の符号の付いたdouble値を返します。
戻り値は、この範囲からの一様分布によって擬似乱数的に選択されます。
2.public char charAt(int index)
指定されたインデックスのchar値を返します。
使用例
package com.arkgame.study.it;
public class RandStr {
      private static String target = "456789abcdefABCDEF#!?";
      private static int count = 8;
      public static void main(String[] args) {
            String result = randStrFunc();
            System.out.println("指定文字列範囲でランダム文字生成結果\n" + result);
      }
      // rand string create
      public static String randStrFunc() {
            StringBuffer sb = new StringBuffer(count);
            String res;
            int randPos;
            for (int i = 0; i < count; i++) {
               //ランダムインデックス取得
                  randPos = (int) (Math.random() * target.length());
                  sb.append(target.charAt(randPos));
            }
            res = sb.toString();
            return res;
      }
}
結果
指定文字列範囲でランダム文字生成結果 fb?CEFED