import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class RandomNum {
public static void main(String[] args) throws FileNotFoundException {
Random random = new Random();
List<String> entries = new ArrayList<>();
for (int i = 0; i < 50; i++) {
int num = random.nextInt(101);
StringBuilder zimu = new StringBuilder();
String a = "abcdefghijklmnopqrstuvwxyz";
for (int e = 0; e < num; e++) {
int index = random.nextInt(a.length());
zimu.append(a.charAt(index));
}
String entryString = "随机数: " + num;
if (num > 0) {
entryString += " 随机字母: " + zimu.toString();
}
entries.add(entryString);
}
// 提取数字排序
Collections.sort(entries, (s1, s2) -> {
int startIndex1 = s1.indexOf("随机数: ") + 4;
int endIndex1 = s1.indexOf(" 随机字母:", startIndex1); // 如果找不到则返回-1
if (endIndex1 == -1) {
endIndex1 = s1.length(); // 如果没有" 随机字母:",则取整个字符串的长度
}
String numStr1 = s1.substring(startIndex1, endIndex1).trim(); // 去除可能的前后空格
int startIndex2 = s2.indexOf("随机数: ") + 4;
int endIndex2 = s2.indexOf(" 随机字母:", startIndex2);
if (endIndex2 == -1) {
endIndex2 = s2.length();
}
String numStr2 = s2.substring(startIndex2, endIndex2).trim();
//比较
int num1 = Integer.parseInt(numStr1);
int num2 = Integer.parseInt(numStr2);
return Integer.compare(num1, num2);
});
//打印
PrintStream ps = new PrintStream("D:\\hepeihuan.txt");
System.setOut(ps);
for (String entry : entries) {
System.out.println(entry);
}
ps.close();
}
}
注意!!部分内容由文心一言提供!主要是 //提取数字排序 这一部分
标签:java,String,int,s2,字母,随机,import,s1,数字 From: https://blog.csdn.net/Dcole/article/details/140110421