我解决了一个问题,在给定初始日期和最终日期的情况下,它会返回它们之间的天数。
我刚刚结束,我的回答似乎是正确的,但它说在某些输入中,我读取年份的方法失败了,它会引发异常。
这是我的阅读日期并将其解析为整数的代码:
String si = in.nextLine();
String sf = in.nextLine();
int di = Integer.parseInt(si.substring(0, 2));
int mi = Integer.parseInt(si.substring(3, 5));
int ai = Integer.parseInt(si.substring(6, si.length()));
int df = Integer.parseInt(sf.substring(0, 2));
int mf = Integer.parseInt(sf.substring(3, 5));
int af = Integer.parseInt(sf.substring(6, sf.length()));
日期以XX / XX / XXXX格式给出(仅为安全起见,我使用s.length读取年份以涵盖年份<1000或> 9999的情况)
此代码中的内容可以在读取该格式的年份时抛出异常吗?
答案 0 :(得分:1)
以下代码段可以很好地运行:
try {
System.out.println("Entered Dates::\n");
Scanner in = new Scanner(System.in);
String si = in.nextLine();
if (Pattern.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d", si)) {
int di = Integer.parseInt(si.substring(0, 2));
int mi = Integer.parseInt(si.substring(3, 5));
int ai = Integer.parseInt(si.substring(6, si.length()));
System.out.println("1st Date Accepted : " + di + "-" + mi + "-" + ai);
}else{
System.out.println("Entered 1st Date incorrect");
}
String sf = in.nextLine();
if (Pattern.matches("\\d\\d/\\d\\d/\\d\\d\\d\\d", sf)) {
int df = Integer.parseInt(sf.substring(0, 2));
int mf = Integer.parseInt(sf.substring(3, 5));
int af = Integer.parseInt(sf.substring(6, sf.length()));
System.out.println("2nd Date Accepted : " + df + "-" + mf + "-" + af);
}else{
System.out.println("Entered 2nd Date incorrect");
}
} catch (Exception e) {
System.out.println("Exception occurred: " + e);
}