Day of the Year Assuming that a year has 365 days, write a class named DayOfYear
ID: 3914702 • Letter: D
Question
Day of the Year Assuming that a year has 365 days, write a class named DayOfYear that takes an integer representing a day of the year and translates it to a string consisting of the month followed by day of the month. For example, Day 2 would be January 2 Day 32 would be February 1. Day 365 would be December 31 The constructor for the class should take as parameter an integer representing the day of the year, and the class should have a member function print) that prints the day in the month-day format. The class should have an integer member variable to represent the day and should have static member variables of type string to assist in the translation from the integer format to the month-day format Test your class by inputting various integers representing days and printing out their representation in the month-day format.Explanation / Answer
class Main {
public static void main(String[] args) {
DayOfYear a = new DayOfYear(2);
DayOfYear b = new DayOfYear(32);
DayOfYear c = new DayOfYear(365);
}
}
class DayOfYear{
// Declared static array of strings
static String[] months = new String[]{"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
int day;
// constructor
DayOfYear(int day){
this.day = day;
print();
}
// method that prints
void print(){
// to know the number of days in each month
int[] days = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int now = 0;
int month = 0;
for(int i=0; i<12; i++)
{
// as long as there are enough days to be considered, tracking and moving to next month
if(now < day && day-now > days[month])
{
month++;
now += days[i];
}
// finally printing output and breaking the loop
else
{
System.out.printf("Day %d would be %s %d ",day, months[month], day-now);
break;
}
}
}
}
/*SAMPLE OUTPUT
Day 2 would be January 2
Day 32 would be February 1
Day 365 would be December 31
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.