【发布时间】:2019-09-27 17:20:39
【问题描述】:
对于家庭作业,我想在 Jave 程序中计算日期在一年中的第 n 天。
因此,用户给出一个日期,然后它会告诉您这是一年中的第几天。所以 2019 年 1 月 1 日是第一天。 我已经有一个函数可以给出一个月的天数。此函数还考虑闰年。 所以我只需要一个函数来返回一年中的天数。 我想的,我必须做的,但它不起作用,因为我不能减少一个月:
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 ;
import java.util.Scanner;
public class Easter
{
public static void main(String[] arguments)
{
Scanner scanner=new Scanner(System.in);
System.out.println("Enter the day month and year with spaces in between:");
int day=scanner.nextInt();
int monthNumber=scanner.nextInt();
Month month=Month.month(monthNumber);
int year=scanner.nextInt();
System.out.println("The month "+month+" has "+numberOfDaysInMonth(year,month)+" days in year "+year);
System.out.println("The number of this date in a year:"+dayNumberInYear(day,month,year));
scanner.close();
}
static boolean isLeapYear(int year)
{
if(year%100==0)
year=year/100;
if(year%4==0)
return true;
return false;
}
static int numberOfDaysInMonth(int year, Month month)
{
switch(month)
{
case APRIL:
case JUNE:
case SEPTEMBER:
case NOVEMBER:
return 30;
case FEBRUARY:
if(isLeapYear(year))
return 29;
return 28;
default:
return 31;
}
}
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;
}
}
已经有一个预制类 Month.java: 包;
public enum Month {
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE, JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
public int number()
{
return ordinal()+1;
}
public static Month month(int number)
{
return values()[number-1];
}
}
【问题讨论】:
-
查看了
LocalDate.of(year, month, day).getDayOfYear()?还是必须重新发明轮子? -
@ernest_k 我添加了一些新信息。但是我不允许使用 Date 类等。所以我猜它必须发生在 for 循环中..
-
您需要找到完整格式的日期,即 dd-mm-yy 的天数?
-
@singhV 是的,比如一月一日的数字总是1,闰年的三月一日的数字是61,非闰年是60 .但我已经知道什么时候是闰年。我只需要一个计算天数的for循环。我希望我解释得足够好
-
请注明您可以使用什么,以便我们根据您的要求回答。
标签: java for-loop days dayofmonth