Java Program To Find Number Of Days In A Month
Chapter:
Miscellaneous
Last Updated:
11-08-2023 17:01:16 UTC
Program:
/* ............... START ............... */
import java.util.Scanner;
public class DaysInMonth {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter year: ");
int year = scanner.nextInt();
System.out.print("Enter month (1-12): ");
int month = scanner.nextInt();
int numberOfDays = getNumberOfDays(year, month);
if (numberOfDays == -1) {
System.out.println("Invalid month input.");
} else {
System.out.println("Number of days in the selected month: " + numberOfDays);
}
scanner.close();
}
public static int getNumberOfDays(int year, int month) {
if (month < 1 || month > 12) {
return -1; // Invalid month input
}
int[] daysInMonth = {
31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
// Adjust for leap year
if (month == 2 && isLeapYear(year)) {
return 29;
}
return daysInMonth[month - 1];
}
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
/* ............... END ............... */
Output
Enter year: 2023
Enter month (1-12): 7
Number of days in the selected month: 31
----Another Sample output------------------
Enter year: 2024
Enter month (1-12): 2
Number of days in the selected month: 29
Notes:
-
This program prompts the user to input a year and a month, then calculates the number of days in that month, accounting for leap years. It uses an array daysInMonth to store the number of days in each month, and the function isLeapYear to determine if a year is a leap year. The getNumberOfDays function returns the number of days for the given month and year, and it handles invalid month inputs by returning -1.