生成隨機(jī)字符串的2種方法,請(qǐng)多多指教,還能不能繼續(xù)優(yōu)化
// 方法一利用ASCII碼:生成10個(gè)隨機(jī)字符串,且長(zhǎng)度不大于10,然后添加進(jìn)List集合
public void testSort2() {
List<String> list = new ArrayList<>();
Random random = new Random();
int temp = 0;
for (int k = 0; k < 10; k++) {
int n;
do {
n = random.nextInt(11);
} while (n == 0);
String str = "";
for (int i = 0; i < n; i++) {
do {
temp = random.nextInt(123);
} while (temp < 48 || (temp > 57) && (temp < 65) || (temp > 90) && (temp < 97));
char ch = (char) temp;
str += ch;
}
list.add(str);
}
System.out.println("排序前:" + list);
Collections.sort(list);
System.out.println("排序后:" + list);
// Collections.sort(list);
// for (String str : list) {
// System.out.print(str + " ");
// }
}
// 方法二利用StringBuilder類:生成10個(gè)隨機(jī)字符串,且長(zhǎng)度不大于10,然后添加進(jìn)List集合
public void testSort3() {
List<String> list = new ArrayList<>();
Random random = new Random();
String strList="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
for (int i = 0; i < 10; i++) {
StringBuilder str = new StringBuilder();
int n;
do {
n = random.nextInt(11);
} while (n == 0);
do {
for (int j = 0; j < n; j++) {
int temp = random.nextInt(62);
str.append(strList.charAt(temp));
}
} while (list.contains(str.toString()));
list.add(str.toString());
}
System.out.println("排序前:" + list);
Collections.sort(list);
System.out.println("排序后:" + list);
}
2017-02-04
小白只看得懂第二種方法,大神活學(xué)活用,深感慚愧哎、小弟受教了。奈何腦容量太小(∩_∩)別說(shuō)如答主運(yùn)用自如了,知識(shí)點(diǎn)都還沒(méi)整理過(guò)來(lái)!佩服佩服!
2016-10-12
int n;
do {
n = random.nextInt(11);
} while (n == 0);
String str = "";
for (int i = 0; i < n; i++)?
第一個(gè)方法 這一段的do-while 可以刪掉 ?把or循環(huán)的int i=0 改成i=-1
2016-09-26
看錯(cuò)了不好意思 == 我自己弄錯(cuò)
2016-09-26
好像和老師的要求有一點(diǎn)偏差第二種方法
2016-08-15
寫的不錯(cuò),這么基礎(chǔ)的代碼也沒(méi)必要再繼續(xù)優(yōu)化了