「Java」ランダム文字列を生成するサンプル
説明
public static double random()
0.0以上で1.0より小さい、正の符号の付いたdouble値を返します。
public char charAt(int index)
指定されたインデックスのchar値を返します。
使用例
package com.arkgame.study.javlesson;
public class RandstrCreate {
public static final String target = "ABCDEFGHabcdefgh1234567890";
public static void main(String[] args) {
String result = getRandStr(target, 8);
System.out.println("ランダムな文字列: " + result);
}
// ランダム文字列の生成
public static String getRandStr(String str, int len) {
StringBuffer sb = new StringBuffer(len);
for (int i = 0; i < len; i++) {
// Math.random 0.0以上で1.0より小さい、正の符号の付いたdouble値を返します
int val = (int) (Math.random() * str.length());
sb.append(str.charAt(val));
}
return sb.toString();
}
}
実行結果
ランダムな文字列: 4ahB9e9a