「Java」ランダム文字列を生成するサンプル

2021年2月9日

説明
public static double random()
0.0以上で1.0より小さい、正の符号の付いたdouble値を返します。
public char charAt(int index)
指定されたインデックスのchar値を返します。
使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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();
}
}
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(); } }
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

Java

Posted by arkgame