在 Java 中生成一个随机字符串
首先,让我们声明一个字符串数组并初始化 −
String[] strArr = { "P", "Q", "R", "S","T", "U", "V", "W" };
现在,创建一个 Random 对象 −
Random rand = new Random();
生成随机字符串 −
int res = rand.nextInt(strArr.length);
示例
import java.util.Random; public class Demo { public static void main(String[] args) { String[] strArr = { "P", "Q", "R", "S","T", "U", "V", "W" }; Random rand = new Random(); int res = rand.nextInt(strArr.length); System.out.println("Displaying a random string = " + strArr[res]); } }
输出
Displaying a random string = R
让我们再次运行它以获得不同的随机字符串 −
Displaying a random string = Q
广告