exit
并退出。注意:处理输入的时候,全部使用Scanner
的nextLine()
方法,以免出错。
输入样例:
6
410425198309308225
320203197206115011
431227196108033146
330226196605054190
34080019810819327X
320111197112301539
sort1
sort2
e
输出样例:
1961-08-03
1966-05-05
1971-12-30
1972-06-11
1981-08-19
1983-09-30
431227196108033146
330226196605054190
320111197112301539
320203197206115011
34080019810819327X
410425198309308225
exit
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
scanner.nextLine();
List<String> idList = new ArrayList<>();
for (int i = 0; i < n; i++) {
String id = scanner.nextLine();
idList.add(id);
}
String input;
while (true) {
input = scanner.nextLine();
if (input.equals("sort1")) {
sortByIdDate(idList);
} else if (input.equals("sort2")) {
sortById(idList);
} else {
System.out.println("exit");
break;
}
}
scanner.close();
}
public static void sortByIdDate(List<String> idList) {
List<String> sortedList = new ArrayList<>();
//思路:创建一个新的List去存储新的格式:year-month-day;
for (String id : idList) {
String year = id.substring(6, 10);
String month = id.substring(10, 12);
String day = id.substring(12, 14);
String formattedDate = year + "-" + month + "-" + day;
sortedList.add(formattedDate);
}
Collections.sort(sortedList);
//遍历排序后的List
for (String date : sortedList) {
System.out.println(date);
}
}
public static void sortById(List<String> idList) {
List<String> sortedList = new ArrayList<>(idList);
//思路:既然不改变原有输出格式:那就修改比较器的比较条件
Collections.sort(sortedList,new Comparator<String>(){
@Override //重写比较器
public int compare(String id1,String id2){
String sub1 = id1.substring(6,14);
String sub2 = id2.substring(6,14);
return sub1.compareTo(sub2);
//if sub1 < sub2 return -1
//sub1 == sub2 return 0 || sub1>sub2 return 1;
}
});
for(String id:sortedList){
System.out.println(id);
}
}
}