Question: This question is based on Java Programming language. The below java code, displays the calendar for a given month of the year. The program prompts

This question is based on Java Programming language.

The below java code, displays the calendar for a given month of the year. The program prompts the user to enter the year and the month, then displays the entire calendar for the month. Can you explain the code and its functions ? you can explain in paragraph or point form.

//Java code

// Header file to take user input

import java.util.Scanner;

//main class

public class Main

{

//method is used to check days for the month

public static int dayOfMonth(int mon, int day, int yr) {

int y = yr - (14 - mon) / 12;

int x = y + y/4 - y/100 + y/400;

int m = mon + 12 * ((14 - mon) / 12) - 2;

int d = (day + x + (31*m)/12) % 7;

return d; //return day of month

}

//function is used to check whether the year is leap year or not

public static boolean leapYear(int yr) {

//check using if-else

if ((yr % 4 == 0) && (yr % 100 != 0))

return true; //return true if not a leapYear

if (yr % 400 == 0)

return true; //return true if not a leapYear

return false; //return false if not a leapYear

}

//main method

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

//ask for user input

System.out.print("Enter full year (e.g., 2022): ");

int yr = in.nextInt(); //user input for year

System.out.print("Enter month in number between 1 and 12: ");

int mon = in.nextInt(); //user input for month

//name of each month, first is blank so that january is in the first index

String[] month = {"", "January", "February", "March", "April", "May", "June",

"July", "August", "September", "October", "November", "December"};

// number of days present in each month

int[] days = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

// checking for leap year

if (mon == 2 && leapYear(yr)) days[mon] = 29;

// month name and days name

System.out.println(" " + month[mon] + " " + yr);

System.out.println("----------------------------");

System.out.println("Sun Mon Tue Wed Thu Fri Sat");

// first day

int d = dayOfMonth(mon, 1, yr);

// printing the calendar

for (int i = 0; i < d; i++)

System.out.print(" ");

for (int i = 1; i <= days[mon]; i++) {

System.out.printf("%3d ", i);

if (((i + d) % 7 == 0) || (i == days[mon])) System.out.println();

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!