×

Java Programs

Java Practice

Java program to find the number of days in a month using a switch statement

Given/input month, we have to find the number of days in a month using a switch statement.
Submitted by Nidhi, on March 03, 2022

Problem statement

In this program, we will read the month number from the user and find the number of days in a given month using a switch statement.

Source Code

The source code to find the number of days in a month using the switch statement is given below. The given program is compiled and executed successfully.

// Java program to find the number of days in a month 
// using a switch statement

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SN = new Scanner(System.in);

    int month = 0;
    int days;

    System.out.printf("Enter month number: ");
    month = SN.nextInt();

    switch (month) {
    case 4:
    case 6:
    case 9:
    case 11:
      days = 30;
      break;

    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
      days = 31;
      break;

    case 2:
      days = 28;
      break;

    default:
      days = 0;
      break;
    }

    if (days != 0)
      System.out.printf("Number of days in %d month is: %d\n", month, days);
    else
      System.out.printf("You have entered an invalid month!!!\n");
  }
}

Output

Enter month number: 4
Number of days in 4 month is: 30

Explanation

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we read a month number from the user using Scanner class. Then we found the number of days in a given month and printed the result.

Java Basic Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.