让我们首先声明一个字符串数组并初始化-
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