ADVERTISEMENT
ADVERTISEMENT

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 Solution:

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.

Program/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 »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.