Reputation: 27
Define a Java method that takes three integer values (a month, a day, and a year) as arguments and returns the number of that day in the year (an integer between 1 and 365, or 366 for leap years). Your method should have the following header: public static int dayNum (int month, int day, int year) To calculate the day number for a given date, use the following formula:
a. dayNum = 31 * (month - 1) + day
b. If the month is after February (2), then subtract (4 * month + 23)/10 from dayNum.
c. If the year is a leap year and the date is after February 29, add 1 to dayNum.
For example, consider March 2, 2000. dayNum is 31 * (3 - 1) + 2, or 64. March comes after February, so we subtract (4 * 3 - 23)/10, or 35/10, or 3 (remember to use integer division, which truncates the remainder). This gives us a day number of 61. However, 2000 was a leap year, and March 2 follows February 29, so we add 1 to dayNum. Our final answer tells us that March 2, 2000, was the 62nd day of the year.
I keep getting inaccurate results when i test this method i did . If i enter march 2nd 2000 it tells me its the 64th day and if i enter febuary 29th it tells me that its the 57th day. Any modifications to my code that work with the specs of the assignment and explanation on what i did wrong would be much appreciated.
public static int dayNum (int month, int day, int year)
{
int dayNum;
dayNum = 31 * (month - 1) + day;
if(month==2)
{
dayNum = dayNum - (4 * month + 23)/10;
if(((year % 4==0 || year % 400 == 0 && (year % 100 != 0)))&&(month>2))
{
dayNum= dayNum + 1;
}
}
return dayNum;
Upvotes: 0
Views: 370
Reputation: 347204
"March comes after February", but your if
statement only checks for Feb?
if(month==2)
You need to check for all the months that fall after Feb
if(month >= 3)
or
if(month > 2)
Upvotes: 1