Finding the number of days in a month required basic knowledge of conditional statements. In Java, programmers can easily find out a number of days by using "if-else" and "Switch" concepts of conditional statements. We all know there are 12 months in a year and each month has 29-31 days.
In the case of Leap year which comes in the gap of 4 years, February has only 28 days. By considering all the information, the programmer can write a java program for finding the numbers of days in a Month (Including Leap Year). So let's begin.
Question
Write a Java program to find the number of days in a month.
Code
public class Numberofdayinmonth {
public static void main (String args[]){
Scanner input = new Scanner(System.in);
int number_Of_DaysInMonth = 0;
String MonthOfName = "Unknown";
System.out.print("Input a month number: ");
int month = input.nextInt();
System.out.print("Input a year: ");
int year = input.nextInt();
switch (month) {
case 1:
MonthOfName = "January";
number_Of_DaysInMonth = 31;
break;
case 2:
MonthOfName = "February";
if ((year % 400 == 0) || ((year % 4 == 0) &&
(year % 100 != 0))) {
number_Of_DaysInMonth = 29;
} else {
number_Of_DaysInMonth = 28;
}
break;
case 3:
MonthOfName = "March";
number_Of_DaysInMonth = 31;
break;
case 4:
MonthOfName = "April";
number_Of_DaysInMonth = 30;
break;
case 5:
MonthOfName = "May";
number_Of_DaysInMonth = 31;
break;
case 6:
MonthOfName = "June";
number_Of_DaysInMonth = 30;
break;
case 7:
MonthOfName = "July";
number_Of_DaysInMonth = 31;
break;
case 8:
MonthOfName = "August";
number_Of_DaysInMonth = 31;
break;
case 9:
MonthOfName = "September";
number_Of_DaysInMonth = 30;
break;
case 10:
MonthOfName = "October";
number_Of_DaysInMonth = 31;
break;
case 11:
MonthOfName = "November";
number_Of_DaysInMonth = 30;
break;
case 12:
MonthOfName = "December";
number_Of_DaysInMonth = 31;
}
System.out.print(MonthOfName + " " + year + " has " +
number_Of_DaysInMonth + " days\n");
}
}
Output
Input a month number: 4
Input a year: 2026
April 2026 has 30 days
How Code Work
Now it's time to understand the code that how it works.
Steps:
- The programmer has to make class and the main method first. After making a class Scanner Method will be used for taking inputs from the user.
0 Comments