Q:

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

belongs to collection: Java Basic Programs

-1

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to validate date and print weekday of... >>
<< Java program to check whether the number is EVEN o...