要生成随机字母,请将字母设置为强,然后使用将toCharArray()
其转换为字符数组-
"abcdefghijklmnopqrstuvwxyz".toCharArray()
现在,使用nextInt()
从中生成随机字母-
System.out.println("" + "abcdefghijklmnopqrstuvwxyz".toCharArray()[randNum.nextInt("abcdefghijklmnopqrstuvwxyz".toCharArray().length)]);
上面,最初我们创建了一个Random对象-
static Random randNum = new Random();
import java.util.Random; public class Demo { static Random randNum = new Random(); public static void main(String args[]) { System.out.println("Lowercase random letters..."); for (int i = 0; i < 5; i++) { System.out.println("" + "abcdefghijklmnopqrstuvwxyz".toCharArray()[randNum.nextInt("abcdefghijklmnopqrstuvwxyz".toCharArray().length)]); } System.out.println("Uppercase random letters..."); for (int i = 0; i < 5; i++) { System.out.println("" + "ABCDEFGHIJKLMNOPQRSTUVWZYZ".toCharArray()[randNum.nextInt("ABCDEFGHIJKLMNOPQRSTUVWZYZ".toCharArray().length)]); } } }
输出结果
Lowercase random letters... d l h j s Uppercase random letters... B K I Z N