【发布时间】:2018-10-25 20:00:53
【问题描述】:
我有一个作业问题是这样写的:编写一个程序,提示用户输入一个日期(以三个数字的形式:年月日),并使用getDays() 方法来帮助计算从给定日期到新年的天数。以下是一些示例运行:
- 请输入日期:2018 12 20
距离新年还有 12 天。 - 请输入日期:1980 1 5
距离新年还有 362 天。
这是我目前的代码:
public class Lab9Question4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a date: ");
int year = input.nextInt();
int month = input.nextInt();
int days = input.nextInt();
input.close();
long diff = getDays(year, month) - days;
long days_diff = diff + 1;
System.out.println("There are " + days_diff + " day(s) until New Year.");
}
public static int getDays(int year, int month) {
int number_Of_DaysInMonth = 0;
switch (month) {
case 1:
number_Of_DaysInMonth = 31;
break;
case 2:
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
number_Of_DaysInMonth = 29;
} else {
number_Of_DaysInMonth = 28;
}
break;
case 3:
number_Of_DaysInMonth = 31;
break;
case 4:
number_Of_DaysInMonth = 30;
break;
case 5:
number_Of_DaysInMonth = 31;
break;
case 6:
number_Of_DaysInMonth = 30;
break;
case 7:
number_Of_DaysInMonth = 31;
break;
case 8:
number_Of_DaysInMonth = 31;
break;
case 9:
number_Of_DaysInMonth = 30;
break;
case 10:
number_Of_DaysInMonth = 31;
break;
case 11:
number_Of_DaysInMonth = 30;
break;
case 12:
number_Of_DaysInMonth = 31;
}
return number_Of_DaysInMonth;
}
}
我知道我需要在某处使用循环以获取用户输入后的剩余天数并将它们添加到日期差中以获取直到新年的天数,但我不确定在哪里插入循环和里面应该有什么。任何帮助表示赞赏:)
更新:感谢所有快速回答的人,此代码现在可以完美运行!新代码如下,供以后可能需要的任何人使用:
public class Lab9Question4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a date: ");
int year = input.nextInt();
int month = input.nextInt();
int days = input.nextInt();
input.close();
int remainingDays = getDays(month, year) - days + 1;
for (int currentMonth = month; currentMonth <= 12; currentMonth++) {
remainingDays += getDays(year, currentMonth);
}
System.out.println("There are " + remainingDays + " day(s) until New Year.");
}
public static int getDays(int year, int month) {
int number_Of_DaysInMonth = 0;
switch (month) {
case 1:
number_Of_DaysInMonth = 31;
break;
case 2:
if ((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
number_Of_DaysInMonth = 29;
} else {
number_Of_DaysInMonth = 28;
}
break;
case 3:
number_Of_DaysInMonth = 31;
break;
case 4:
number_Of_DaysInMonth = 30;
break;
case 5:
number_Of_DaysInMonth = 31;
break;
case 6:
number_Of_DaysInMonth = 30;
break;
case 7:
number_Of_DaysInMonth = 31;
break;
case 8:
number_Of_DaysInMonth = 31;
break;
case 9:
number_Of_DaysInMonth = 30;
break;
case 10:
number_Of_DaysInMonth = 31;
break;
case 11:
number_Of_DaysInMonth = 30;
break;
case 12:
number_Of_DaysInMonth = 31;
}
return number_Of_DaysInMonth;
}
}
【问题讨论】:
标签: java