在 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
廣告