Programming Examples
Java program to print number of days in given month serial number
Java program that prints the number of days in a month based on the month serial number (1 for January, 2 for February, ..., 12 for December) using a switch statement:
Solution
import java.util.Scanner;
public class DaysInMonthSwitch
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter the month number (1-12): ");
int monthNumber = sc.nextInt();
int daysInMonth;
switch (monthNumber)
{
case 1: // January
case 3: // March
case 5: // May
case 7: // July
case 8: // August
case 10: // October
case 12: // December
System.out.println("Number of days in month " + monthNumber + " is: 31")
break;
case 4: // April
case 6: // June
case 9: // September
case 11: // November
System.out.println("Number of days in month " + monthNumber + " is: 30")
break;
case 2: // February
System.out.println("Number of days in month " + monthNumber + " is: 28 or 29")
break;
default:
System.out.println("Invalid month number. Please enter a number between 1 and 12.");
break;
}
}
}
Output