我想在Jave程序中计算日期在一年中的第n个数字。因此,用户给定一个日期,然后告诉它一年中的天数。因此,2019年1月1日是第一天。我已经有一个函数可以给出一个月中的天数。此功能还考虑leap年。因此,我只需要一个返回一年中天数的函数。我想,我必须做,但是由于我不能减少一个月,所以它不起作用:
static int dayNumberInYear(int day, Month month, int year)
{
while(month!=Month.JANUARY)
{
int dayNumberInYear=dayNumberInYear+numberOfDaysInMonth(year,month);
Month month = month(-1);
}
return dayNumberInYear(day,month,year)+day;
}
我知道这是不对的,所以我希望有人可以帮助我。我认为for循环更好,但我不知道如何。第一行static int dayNumberInYear(int day, Month month, int year)
不允许更改,因此必须是第一行。我不允许使用Java JRE日期操作类,例如Calendar,日期等!
我是初学者,所以我希望有人可以帮助我。
package SO;
import java.time.Month;
public class test {
//below array contain number of total days in that month(non leap year).
static int arrTotal[] = { 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 };
public static void main(String[] args) {
System.out.println(dayNumberInYear(3, Month.MARCH, 2019));
}
static int dayNumberInYear(int day, Month month, int year) {
int dayNumberInYear = day + numberOfDaysInMonth(year, month);
return dayNumberInYear;
}
private static int numberOfDaysInMonth(int year, Month month) {
int add = 0;
if (year % 4 == 0)
add++;
int a = month.getValue();
return arrTotal[(a - 2)] + add;
}
}
您似乎想要的想法是一种递归方法,该方法逐月递减。我不确定您的代码中的Month类做什么,因此为了演示起见,我将其视为一个整数。
static int dayNumberInYear(int day, int month, int year)
{
if(month != 1) {
return day + dayNumberInYear(numberOfDaysInMonth(month-1, year), month-1, year);
} else {
return day;
}
}
请注意,在这种递归方法中,基本情况是现在是一月,而我们只是返回一月的当前日期。否则,我们将添加当前月份的日期,然后添加每个上个月的所有日期。
也可以作为for循环来完成。
static int dayNumberInYearByLoop(int day, int month, int year) {
int totalDays = day;
for (int i = month-1;i>=1;i--) {
totalDays += numberOfDaysInMonth(month, year);
}
return totalDays;
}
您可以在这里弄乱我的代码:https://repl.it/repls/ConcreteDarkgreenSequence