我正在用 Java 编写一个程序,它基本上可以找到 2 个特定日期之间的天数。用户输入 DD/MM/YYYY 格式的两个日期,我取日/月/年的子字符串并计算 2 之间的天数。我还做了一种验证,如果格式错误(例如 d/mm/yyyy)然后该人必须以正确的格式重写日期。我通过确保日期中的 / 处于正确位置来做到这一点。如果 4 / 匹配,那么一个布尔变量给我真,程序继续,如果不是,它给我假,它再次询问日期。
问题是它总是给我错误,即使那样,它也没有重新循环。
import java.util.*;
public class DateDifference {
int day1, day2, month1, month2, year1, year2;
String startdate, enddate, day1S, day2S, month1S, month2S, year1S, year2S;
String datevalidation = "/";
boolean dval;
public static void main(String args[]){
DateDifference difference = new DateDifference();
}
DateDifference() {
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
Scanner sc = new Scanner (System.in);
do {
System.out.println("Enter Start Date [dd/mm/yyyy]:");
startdate = sc.next();
System.out.println("Enter End Date [dd/mm/yyyy]:");
enddate = sc.next();
int l1 = startdate.length();
int l2 = enddate.length();
day1S = startdate.substring(0,2);
month1S = startdate.substring(3,5);
year1S = startdate.substring(6,l1);
day2S = enddate.substring(0,2);
month2S = enddate.substring(3,5);
year2S = enddate.substring(6,l2);
if (startdate.substring(2,3).equals(datevalidation) & startdate.substring(5,6).equals(datevalidation) & enddate.substring(2,3).equals(datevalidation) & enddate.substring(5,6).equals(datevalidation))
dval = true;
else
dval = false;
System.out.println("Wrong date format. Try again");
} while (dval = false);
day1 = Integer.parseInt(day1S);
month1 = Integer.parseInt(month1S);
year1 = Integer.parseInt(year1S);
day2 = Integer.parseInt(day2S);
month2 = Integer.parseInt(month2S);
year2 = Integer.parseInt(year2S);
cal1.set(year1, month1 - 1, day1);
cal2.set(year2, month2 - 1,day2);
System.out.println("Days= "+daysBetween(cal1.getTime(),cal2.getTime()));
}
public int daysBetween(Date cal1, Date cal2){
return (int)( (cal2.getTime() - cal1.getTime()) / (1000 * 60 * 60 * 24));
}
}
以下是一些关于它是如何工作的图片:
输入正确时:http: //vvcap.net/db/2100RYdaSM1T6EXLqgq5.png
当输入不正确时:http: //vvcap.net/db/9qSEwDKSTIdLAWmxS_Cy.png
如果不正确,它只会在尝试将 1/ 设为整数时卡住,我可以理解。
有什么帮助吗?
非常感谢。