问候!我已经处理了预期可以处理该程序的以下代码。如果用户手动指定的到期日期在当前日期之前,则程序应终止,否则程序将显示剩余多少时间。
当我输入有效日期作为当前日期时,即年份:2014,月份:3,日期:7
符合我的期望,该程序应该已经终止,但显示为1年,等等。我在哪里做错。
// Sets GregorianCalendar expiryDate object
static void setTrial(){
System.out.println("\n----- SET TRIAL DATE ----\n");
System.out.print("Year : ");
int year = new Scanner(System.in).nextInt();
System.out.print("Month : ");
int month = new Scanner(System.in).nextInt();
System.out.print("Day : ");
int day = new Scanner(System.in).nextInt();
expiryDate = new GregorianCalendar(year, month, day);
}
// Validates the expiryDate with current GregorianCalendar object
static void validate(){
System.out.print("\n----- VALIDATING THE PRODUCT ----\n");
GregorianCalendar current = new GregorianCalendar();
if( current.after(expiryDate) ){
System.out.println("\nYour trial period is expired. Please buy the product.");
}else{
GregorianCalendar temp = new GregorianCalendar(expiryDate.get(GregorianCalendar.YEAR) -
current.get(GregorianCalendar.YEAR),
expiryDate.get(GregorianCalendar.MONTH) -
current.get(GregorianCalendar.MONTH),
expiryDate.get(GregorianCalendar.DAY_OF_MONTH) -
current.get(GregorianCalendar.DAY_OF_MONTH));
System.out.println("\nYou still have " +
temp.get(GregorianCalendar.YEAR) + " years, " +
temp.get(GregorianCalendar.MONTH) + " months, " +
temp.get(GregorianCalendar.DAY_OF_MONTH) +
" days remaining... \n\nPlease buy the product before it expires!");
}
最佳答案
改变以下expiryDate = new GregorianCalendar(year, month, day);
至GregorianCalendar expiryDate = new GregorianCalendar(year, month-1, day);
和System.out.println("\nYou still have " + temp.get(GregorianCalendar.YEAR) + " years, " + temp.get(GregorianCalendar.MONTH) + " months, " + temp.get(GregorianCalendar.DAY_OF_MONTH) + " days remaining... \n\nPlease buy the product before it expires!");
至System.out.println("\nYou still have " + temp.get(GregorianCalendar.YEAR-1) + " years, " + temp.get(GregorianCalendar.MONTH) + " months, " + temp.get(GregorianCalendar.DAY_OF_MONTH) + " days remaining... \n\nPlease buy the product before it expires!");
关于java - 产品有效期(意外输出),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22252514/