Write a program to Find the number of days in a month using a switch statement
This Java code prompts the user to input a month number and then uses a switch statement to determine the number of days in that month. Here's a line-by-line explanation:
- import java.util.Scanner; - imports the Scanner class from the java.util package, which is used for user input.
- public class Number_OfDays - defines a public class called Number_OfDays.
- public static void main(String[] args) - the main method that serves as the entry point for the Java program.
- Scanner input = new Scanner(System.in); - creates a new Scanner object to read user input from the console.
- int mon = 0; - declares and initializes an integer variable mon to zero.
- int days; - declares an integer variable days without initializing it.
- System.out.printf("Enter the Month Number : "); - prints a message to prompt the user to input a month number.
- mon = input.nextInt(); - reads an integer input from the user and assigns it to the mon variable.
- switch(mon) - starts a switch statement based on the value of the mon variable.
- case 1: - the first case is executed if mon is equal to 1.
- case 3: - the next case is executed if mon is equal to 3.
- case 5: - and so on, for each month with 31 days.
- System.out.print("Number of Days 31.."); - if the month has 31 days, this message is printed to the console.
- break; - terminates the switch statement.
- case 4: - the next case is executed if mon is equal to 4.
- case 6: - and so on, for each month with 30 days.
- System.out.print("Number of Days 30.."); - if the month has 30 days, this message is printed to the console.
- break; - terminates the switch statement.
- case 2: - the next case is executed if mon is equal to 2.
- days = 28; - assigns the value 28 to the days variable, since February has 28 days in a non-leap year.
- break; - terminates the switch statement.
- default: - if none of the previous cases are executed, this default case is executed.
- System.out.printf("Invalid...Please Enter the 1 to 12..."); - prints an error message to the console if the user inputs a value outside the range of 1 to 12.
- break; - terminates the switch statement.
- } - closes the switch statement.
- } - closes the main method.
- } - closes the Number_OfDays class.
Source Code
import java.util.Scanner;
public class Number_OfDays
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
int mon = 0;
int days;
System.out.printf("Enter the Month Number : ");
mon = input.nextInt();
switch(mon)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.print("Number of Days 31..");
break;
case 4:
case 6:
case 9:
case 11:
System.out.print("Number of Days 30..");
break;
case 2:
days = 28;
break;
default:
System.out.printf("Invalid...Please Enter the 1 to 12...");
break;
}
}
}
Output
Enter the Month Number : 10
Number of Days 31..