随机生成26个字母中(一个或多个)的字母、数字
package com.test1; public class Test3 { public static void main(String[] args) { //需要生成几位 int n = 1; //最终生成的字符串 String str = ""; for (int i = 0; i < n; i++) { str = str + (char)(Math.random()*26+'a'); } System.out.println(str); //--------------------------------数字---------------------------------------- Random random =new Random(); StringBuilder a = new StringBuilder(); for (int i = 0; i <n; i++) { a.append(String.valueOf(random.nextInt(10))); //区间[0,10) } System.out.println(a); } } /* 特别注意的点: 1, ‘A’ 是随机生成大写的26个随机字母 2, ‘a’ 是随机生成小写的26个随机字母 3, n 的值变化,是生成多少位随机数 n = 1,则随机生成一位; n= 2,则随机生成2位,依次类推… */
生成数字:0-9
c = (char)(Math.random()*('9' - '0' + 1) + '0');
生成小写字母:a-z
c = (char)(Math.random()*('z' - 'a' + 1) + 'a');
生成大写字母:A-Z
c = (char)(Math.random()*('Z' - 'A' + 1) + 'A');
注意事项:
在利用对象方法时,尽量不要重复new一个对象调用,对象的生成会占用时间和内存。
可以自行测试:
long start = System.currentTimeMillis();long end = System.currentTimeMillis();
System.out.println(end-start);
例如上处换成:----这样消耗的时间差别将近2.5倍,个人自测时间。
一个对象:7040ms
重复对象:19373ms
StringBuilder a = new StringBuilder();
for (int i = 0; i <400000000; i++) {
a.append(new Random().nextInt(10)); //区间[0,10)
}
System.out.println(a);
浙公网安备 33010602011771号