AcWing 1229. 日期问题(java异常版)
原题链接
简单
作者:
zshprint
,
2021-04-06 11:52:40
,
所有人可见
,
阅读 370
利用java异常机制对日期进行判断
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author zhangshuohua
*/
public class Main {
static int[] a = {0, 2, 2};
static int[] b = {1, 0, 1};
static int[] c = {2, 1, 0};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String date = sc.nextLine();
String[] split = date.split("/");
ArrayList<String> list = new ArrayList<>();
for (int i = 0; i < 3; i++) {
String s = "19" + split[a[i]] + "-" + split[b[i]] + "-" + split[c[i]];
if (check(s) && !list.contains(s)) {
list.add(s);
}
s = "20" + split[a[i]] + "-" + split[b[i]] + "-" + split[c[i]];
if (check(s) && !list.contains(s)) {
list.add(s);
}
}
Collections.sort(list);
for (String s : list) {
System.out.println(s);
}
}
public static boolean check(String dateString) {
Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
start.set(Calendar.YEAR, 1960);
start.set(Calendar.MONDAY, 1);
start.set(Calendar.DAY_OF_WEEK, 1);
end.set(Calendar.YEAR, 2059);
end.set(Calendar.MONTH, 12);
end.set(Calendar.DAY_OF_WEEK, 31);
simpleDateFormat.setLenient(false);
try {
Date parse = simpleDateFormat.parse(dateString);
if (parse.getTime() - start.getTimeInMillis() < 0 || end.getTimeInMillis() - parse.getTime() < 0) {
return false;
}
return true;
} catch (ParseException e) {
return false;
}
}
}
这个是真的学到了
开始了 实诚点孩子
你去看我的代码,我都是硬判断的,用异常是真的不会