For a homework assignment, I want to calculate the nth number of the day a date is in a year in a Jave program.
So, a user gives a date, and then it tells what number of day this is in a year. So 1st of January 2019, is day 1. I already have a function that gives the number of days in a month. This function also considers leap years. So I only need a function that returns the number of the day in the year. What I thought, I had to do, but it does not work because I can't decrement a month:
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;
}
I know this is not right, so I hope someone can help me.
I think a for-loop is better, but I do not know how. And the first line, static int dayNumberInYear(int day, Month month, int year)
, I am not allowed to change that, so it needs to be this first line.
I am not allowed to use the java JRE date manipulating classes like Calendar,
Date etc!
I am a beginner, so please I hope that someone can help me. Here is the code I have so far:
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;
}
}
There is already a premade class Month.java: package ;
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];
}
}